简体   繁体   English

如何通过React中的API下载文件?

[英]How to download a file through an API in React?

In my react app, I have a component which has a file download button for download a file coming from the Back end. 在我的react应用程序中,我有一个具有文件下载按钮的组件,用于下载来自后端的文件。 I'm using AXIOS for the AJAX call. 我正在使用AXIOS进行AJAX调用。 The problem is, after downloading the file, it is corrupted. 问题是,下载文件后,文件已损坏。 I'm downloading png files and pdf files. 我正在下载png文件和pdf文件。 When I open the downloaded image, it says it's corrupted and downloaded pdf shows white background only. 当我打开下载的图像时,它说它已损坏,并且下载的pdf仅显示白色背景。 How can I download a file correctly? 如何正确下载文件?

** Component:** ** 零件:**

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

As I am not able to add comments so posting as answer. 由于我无法添加评论,因此发布为答案。 I have tried the same thing and posted the question for same in this link . 我尝试过同样的事情,并在此链接中发布了同样的问题。

For post method i get the success with fetch as below. 对于post方法,我通过如下获取成功。

 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*... )

You are getting corrupted file because you are not receiving content as blob or arraybuffer . 您正在损坏文件,因为您没有以blobarraybuffer的形式接收内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM