首页 > 解决方案 > 如何通过 React 中的 API 下载文件?

问题描述

在我的反应应用程序中,我有一个组件,它有一个文件下载按钮,用于下载来自后端的文件。我正在AXIOS用于AJAX通话。问题是,下载文件后,它已损坏。我正在下载png文件和pdf文件。当我打开下载的图像时,它说它已损坏并且下载pdf仅显示白色背景。如何正确下载文件?

** 零件:**

import API from "../../api/api";

class DocumentsTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileId: 4
    };
    this.downloadMapById = this.downloadMapById.bind(this);
  }

  downloadMapById() {
    const type = 1;
    const file_id = this.state.fileId;

    const FileDownload = require("js-file-download");

    API.post("project/files/download", { file_id, type })
      .then(({ data }) => {
        FileDownload(data, "myImage.png");
        console.log("success!", data);
      })
      .catch(err => {
        console.log("AXIOS ERROR: ", err);
      });
  }

  render() {
    return <button onClick={() => this.downloadMapById}>Download</button>;
  }
}

API文件:

import axios from "axios";

const token = localStorage.getItem("token");

export default axios.create({
  baseURL: `${process.env.REACT_APP_BACKEND_BASE_URL}/api/v1/`,
  headers: {
    Authorization: "Bearer " + token,
    "Content-Type": "application/json",
    Accept: "application/json"
  }
});

标签: javascriptreactjsaxios

解决方案


由于我无法添加评论,因此发布为答案。我已经尝试过同样的事情,并在此链接中发布了同样的问题。

对于post方法,我通过fetch获得成功,如下所示。

 fetch("url",
        { 
            method: "POST",
            headers: { "Content-Type": "application/json",'Authorization': 'Bearer ' + window.localStorage["Access_Token"]},
            body:data
        }).then(response => response.blob()).then(response => ...*your code for download*... )

您收到损坏的文件,因为您没有收到blobarraybuffer的内容。


推荐阅读