首页 > 解决方案 > 即使请求成功,下载文件也失败

问题描述

我正在尝试使用 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

请求我可以在响应的正文中看到该文件。但是当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]

任何人都可以告诉什么是错的?为什么即使请求成功,它也没有下载正确的文件?还有其他更简单的方法可以从服务器下载文件吗?

标签: javascriptreactjsblob

解决方案


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

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: "" })
        });
    });
}

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


推荐阅读