Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

** 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:

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"
  }
});
like image 310
David Johns Avatar asked May 20 '19 11:05

David Johns


People also ask

How do I download a file using API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.

How do I download a text file from React?

Download Text file You can enter the required text in the input field and download it as a text file by clicking the download button. A new Blob Object of the MIME type will be created and attaches it to the href of a temporary anchor element and will be triggered programmatically.

How download file from server location react JS?

To download a file with React. js, we can add the download attribute to an anchor element. We just add the download prop to do the download. If we don't want to use an anchor element, we can also use the file-saver package to download our file.


1 Answers

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.

 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.

like image 56
Sandeep Rasgotra Avatar answered Sep 23 '22 06:09

Sandeep Rasgotra