如何通过 React 中的 API 下载文件? [英] How to download a file through an API in React?

查看:32
本文介绍了如何通过 React 中的 API 下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my react app, I have a component which has a file download button for download a file coming from the Back end. I'm using AXIOS for the AJAX call. The problem is, after downloading the file, it is corrupted. I'm downloading png files and pdf files. When I open the downloaded image, it says it's corrupted and downloaded pdf shows white background only. How can I download a file correctly?

** 组件:**

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

推荐答案

由于我无法添加评论,所以发帖作为答案.我已经尝试过同样的事情并在这个 链接.

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.

对于 post 方法,我使用 fetch 取得了成功,如下所示.

For post method i get the success with fetch as below.

 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 形式的内容.

You are getting corrupted file because you are not receiving content as blob or arraybuffer.

这篇关于如何通过 React 中的 API 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆