【问题标题】:Download file with react failed even though the request was successful即使请求成功,下载文件也反应失败
【发布时间】:2021-09-01 06:12:25
【问题描述】:

我正在尝试使用 react 和 node 从客户端中的服务器下载文件。这是我用来在前端实现下载btn的代码:

import React from "react";
import { Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';


class DownloadBtn extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      fileDownloadUrl: ""
    }
  }
  
  dofileDownload(){
    console.log(this.state.fileDownloadUrl);
  }

  handleFile (response){
    console.log(response);
    const blob = new Blob([response]);                   // Step 3
    const fileDownloadUrl = URL.createObjectURL(blob); // Step 4
    this.setState ({fileDownloadUrl: response.url},//fileDownloadUrl}, // Step 5
      () => {
        this.dofileDownload.click();                   // Step 6
        URL.revokeObjectURL(fileDownloadUrl);          // Step 7
        this.setState({fileDownloadUrl: ""})
    })
  }

  handleClick (){
    fetch(this.props.fileName, {
      method: 'GET',
      'content-type': 'application/octet-stream',
    })
    .then((response) => this.handleFile(response));
  }

  render() {
    return (
      <div>
      <Button onClick={() => this.handleClick()} variant="outline-primary">Download</Button>
      <a 
         download={this.props.fileName}
         href={this.state.fileDownloadUrl}
         ref={e=>this.dofileDownload = e}
         >download</a>
      </div>
    );
  }
}

export default DownloadBtn;

服务器正在工作。当我检查时

GET http://localhost:3000/gcode/lucas/1623843541661.gcode

request 我可以在响应的正文中看到该文件。但是当我console.log(response) 我得到:

Response {type: "basic", 
url: "http://localhost:3000/gcode/lucas/1623843541661.gcode", 
redirected: false, 
status: 200, 
ok: true,
body: ReadableStream,
bodyUsed: false,
 …}

下载文件的内容:

[object Response]

谁能告诉我哪里错了?为什么即使请求成功,它也没有下载正确的文件?还有其他更简单的方法可以从服务器下载文件吗?

【问题讨论】:

    标签: javascript reactjs blob downloadfile


    【解决方案1】:

    您应该使用响应对象 (Doc) 提供的blob 方法。

    handleFile 方法替换为:

    handleFile(response) {
        console.log(response);
        response.blob().then((blob) => {
            const fileDownloadUrl = URL.createObjectURL(blob);
            this.setState({ fileDownloadUrl: response.url }, () => {
                this.dofileDownload.click();
                URL.revokeObjectURL(fileDownloadUrl);
                this.setState({ fileDownloadUrl: "" })
            });
        });
    }
    

    Blob 构造函数接受一个包含文件内容的数组 (Doc)。任何不是预期类型的​​值都将转换为字符串。响应对象的默认字符串表示形式是[object Response]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2020-08-23
      相关资源
      最近更新 更多