title: How to download a file through an API in React?
body: <p>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 <code>AXIOS</code> for the <code>AJAX</code> call. <strong>The problem is, after downloading the file, it is corrupted. I'm downloading <code>png</code> files and <code>pdf</code> files. When I open the downloaded image, it says it's corrupted and downloaded <code>pdf</code> shows white background only.</strong> How can I download a file correctly?</p>
  
  <p>** Component:**</p>
  
  <pre class="lang-js prettyprint-override"><code>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 }) =&gt; {
          FileDownload(data, "myImage.png");
          console.log("success!", data);
        })
        .catch(err =&gt; {
          console.log("AXIOS ERROR: ", err);
        });
    }
  
    render() {
      return &lt;button onClick={() =&gt; this.downloadMapById}&gt;Download&lt;/button&gt;;
    }
  }
  </code></pre>
  
  <p><strong>API file:</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>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"
    }
  });
  </code></pre>