What I wanted:

  • send files of any formats from the back-end to the front-end

My tools:

  • axios, express, saveAs

The problem I faced with:

  • Unable to download zip file using axios
  • https://github.com/eligrey/FileSaver.js/issues/156
  • https://github.com/axios/axios/issues/448

Nothing helped me, probably because I did something wrong. But here is a simple and quick solution that I came up with:

//BE
const filename = "my-file-name.json";

const zip = new AdmZip();
zip.addFile(filename, body);
const content = zip.toBuffer();

res.set({
            "Content-Length": Buffer.byteLength(content), //I'm not sure if this is necessary, but it's better to let it be :-)
            "Content-Type": "text/plain",
            "Content-Disposition": `attachment; filename=${filename}.${format}`,
          });
res.status(200).send(content.toString("hex")); //my solution to the problem

//FE
const { headers, data } = await axios.post(myEndpoint);
const headerLine = headers["content-disposition"];
const filename = headerLine.replace(/[\w; ]+filename=/g, "");

const content = Buffer.from(data, "hex");
const blob = new Blob([content], { type: "application/zip" });
saveAs(blob, filename); //file-saver npm package

Answer from pi88a on Stack Overflow
Top answer
1 of 4
3

What I wanted:

  • send files of any formats from the back-end to the front-end

My tools:

  • axios, express, saveAs

The problem I faced with:

  • Unable to download zip file using axios
  • https://github.com/eligrey/FileSaver.js/issues/156
  • https://github.com/axios/axios/issues/448

Nothing helped me, probably because I did something wrong. But here is a simple and quick solution that I came up with:

//BE
const filename = "my-file-name.json";

const zip = new AdmZip();
zip.addFile(filename, body);
const content = zip.toBuffer();

res.set({
            "Content-Length": Buffer.byteLength(content), //I'm not sure if this is necessary, but it's better to let it be :-)
            "Content-Type": "text/plain",
            "Content-Disposition": `attachment; filename=${filename}.${format}`,
          });
res.status(200).send(content.toString("hex")); //my solution to the problem

//FE
const { headers, data } = await axios.post(myEndpoint);
const headerLine = headers["content-disposition"];
const filename = headerLine.replace(/[\w; ]+filename=/g, "");

const content = Buffer.from(data, "hex");
const blob = new Blob([content], { type: "application/zip" });
saveAs(blob, filename); //file-saver npm package

2 of 4
1

Your problem is that you didn't explicitly specify the response type in your PUT request. This should work:

const exportCards = () => {
  axios
    .put(url, {
      ids: ids,
    }, {
      responseType: 'blob'
    })
    .then((res) => { // Now 'res.data' is Blob, not a string
      var file = window.URL.createObjectURL(res.data);
      window.location.assign(file);
    })
    .catch((e) => console.log(e));
};

Discussions

reactjs - Download zip files using axios - Stack Overflow
I am working on a react project where I'm getting a zip file as a response to REST API, I've to download the same and save it in client's machine. The size of the zip file can vary from 100mb to 80... More on stackoverflow.com
🌐 stackoverflow.com
December 26, 2018
How to download files using axios - Stack Overflow
I am using axios for basic http requests like GET and POST, and it works well. Now I need to be able to download Excel files too. Is this possible with axios? If so does anyone have some sample code? If not, what else can I use in a React application to do the same? More on stackoverflow.com
🌐 stackoverflow.com
node.js - Unable to download zip file using axios - Stack Overflow
If I try to open the file, it says invalid zip error. ... I tried it in postman. it is working fine in postman. ... One trick I've used is to get the request working in Postman (which you've done), then click the 'Code' button in the mid-right corner of Postman, which will generate a code snippet to perform the current request in various languages - including Node. There isn't an Axios... More on stackoverflow.com
🌐 stackoverflow.com
February 22, 2018
Zip File downloaded using ReactJs/Axios is corrupted
This is a cross post with my SO question: https://stackoverflow.com/questions/54414054/zip-file-downloaded-from-reactjs-axios-is-corrupted More on reddit.com
🌐 r/javascript
1
2
November 20, 2018
🌐
GitHub
gist.github.com › javilobo8 › 097c30a233786be52070986d8cdb1743
Download files with AJAX (axios) · GitHub
var memory = new MemoryStream(); using (var stream = new FileStream(completeAddress, FileMode.Open)) { stream.CopyTo(memory); } memory.Position = 0; return new MediaOperationFileStreamViewModel() { MediaFileStream = new MediaFileStreamDto() { FileId = mediaInfo.Id, FileName = mediaInfo.Name, ContentType = Service.Helper.MimeType.GetContentType(completeAddress), FileStream = memory } }; The result will return to controller. Below is my React code : axios.create({ baseURL: 'https://localhost:44337/api', timeout: 300000, maxContentLength: 1073741824, }).post('/MediaOperation/DownloadFileStream', { "MediaFileId": item, responseType: 'blob' }).then(fileResult => { const url = window.URL.createObjectURL(new Blob([fileResult.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', currentFileInfo.name); document.body.appendChild(link); link.click(); });
🌐
GitHub
gist.github.com › senthilmpro › 04ea6c086bcb592beb8083214a630548
Download files using Axios.js · GitHub
Download ZIP · Download files using Axios.js · Raw · download-file-axios.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Stack Overflow
stackoverflow.com › questions › 53929886 › download-zip-files-using-axios
reactjs - Download zip files using axios - Stack Overflow
December 26, 2018 - sorry, can't share the code. the api works fine because i have tested the generated request over postman and it downloads the zip file and i'm able to see the content. ... const config = { headers: { Authorization: `Bearer ${token}` }, maxBodyLength: 'Infinity', responseType: 'stream', }; let endpoint = `/api/reports?from=${startDate}&to=${endDate}`; const baseUrl = 'https://api.example.com'; const response = await axios.get(`${baseUrl}${endpoint}`, config); const download_dir = 'config/temp-downloads/'; const currentDate = new Date().toISOString().split('T')[0]; const fileNameWithDate = `${fi
🌐
JetRockets
jetrockets.com › blog › l8dadq8oac-how-to-download-files-with-axios
Downloading Files with Axios in JavaScript: A Simple Guide
March 20, 2019 - export function someFunction(values) { return (dispatch) => { ... const method = 'GET'; const url = 'http://go.api/download_file'; ... axios .request({ url, method, responseType: 'blob', //important }) .then(({ data }) => { const downloadUrl = window.URL.createObjectURL(new Blob([data])); const link = document.createElement('a'); link.href = downloadUrl; link.setAttribute('download', 'file.zip'); //any other extension document.body.appendChild(link); link.click(); link.remove(); }); }; } javascript ·
🌐
Bobby Hadz
bobbyhadz.com › blog › download-file-using-axios
How to download Files and Images using Axios [4 Ways] | bobbyhadz
March 7, 2024 - Every time the button is clicked, the axiosDownloadFile function is called. If you get a TypeError: Failed to fetch and CORS error, click on the link and follow the instructions. When you download a file from a URL, the server sends a Content-Disposition response header that looks similar to the following.
Find elsewhere
Top answer
1 of 16
418
  1. Download the file with Axios as a responseType: 'blob'
  2. Create a file link using the blob in the response from Axios/Server
  3. Create <a> HTML element with a the href linked to the file link created in step 2 & click the link
  4. Clean up the dynamically created file link and HTML element
axios({
    url: 'http://api.dev/file-download', //your url
    method: 'GET',
    responseType: 'blob', // important
}).then((response) => {
    // create file link in browser's memory
    const href = URL.createObjectURL(response.data);

    // create "a" HTML element with href to file & click
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'file.pdf'); //or any other extension
    document.body.appendChild(link);
    link.click();

    // clean up "a" element & remove ObjectURL
    document.body.removeChild(link);
    URL.revokeObjectURL(href);
});

Check out the quirks at https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

Full credits to: https://gist.github.com/javilobo8

More documentation for URL.createObjectURL is available on MDN. It's critical to release the object with URL.revokeObjectURL to prevent a memory leak. In the function above, since we've already downloaded the file, we can immediately revoke the object.

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them.

Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.

2 of 16
188

When response comes with a downloadable file, response headers will be something like:

{
  "Content-Disposition": "attachment;filename=report.xls"
  "Content-Type": "application/octet-stream" // or "application/vnd.ms-excel"
}

What you can do is create a separate component, which will contain a hidden iframe.

import * as React from 'react';

var MyIframe = React.createClass({
 
   render: function() {
       return (
         <div style={{display: 'none'}}>
             <iframe src={this.props.iframeSrc} />
         </div>
       );
   }
});

Now, you can pass the url of the downloadable file as prop to this component. So when this component will receive prop, it will re-render and file will be downloaded.

Edit: You can also use js-file-download module. Link to Github repo

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

Axios({
  url: 'http://localhost/downloadFile',
  method: 'GET',
  responseType: 'blob', // Important
}).then((response) => {
    FileDownload(response.data, 'report.csv');
});
🌐
DEV Community
dev.to › doxomo › how-to-download-files-with-axios-2b8g
How to download files with Axios - DEV Community
July 3, 2019 - export function someFunction(values) { return (dispatch) => { ... const method = 'GET'; const url = 'http://go.api/download_file'; ... axios .request({ url, method, responseType: 'blob', //important }) .then(({ data }) => { const downloadUrl = window.URL.createObjectURL(new Blob([data])); const link = document.createElement('a'); link.href = downloadUrl; link.setAttribute('download', 'file.zip'); //any other extension document.body.appendChild(link); link.click(); link.remove(); }); }; } Subscribe ·
🌐
Reddit
reddit.com › r/javascript › zip file downloaded using reactjs/axios is corrupted
r/javascript on Reddit: Zip File downloaded using ReactJs/Axios is corrupted
November 20, 2018 -

Using React/Axios. I am trying to download a zip file from a Django API. The zip file is always corrupted when I try to unzip it. When I perform the same request on Postman, everything works fine. Here is my code fragment:

        axios
            .post('http://0.0.0.0:8000/sheets/', data,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'responseType': 'arraybuffer'
                    }
                })
            .then(res => {
                console.log(res.data)
                const disposition = res.request.getResponseHeader('Content-Disposition')
                var fileName = "";
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) {
                    fileName = matches[1].replace(/['"]/g, '');
                }
                let blob = new Blob([res.data], { type: 'application/zip' })

                const downloadUrl = URL.createObjectURL(blob)
                let a = document.createElement("a"); 
                a.href = downloadUrl;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();

Am I doing something obviously wrong?

Thanks!

🌐
Stack Overflow
stackoverflow.com › questions › 63989778 › download-single-file-as-pdf-and-multiple-files-as-zip-using-axios-in-react
Download single file as pdf and multiple files as zip using axios in React
September 21, 2020 - try { const res = await axios.get( `${apilink}/download/`, { responseType: "blob", params: body, } ); const url = window.URL.createObjectURL(new Blob([res.data])); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "file.zip"); document.body.appendChild(link); link.click(); } catch (e) { toaster.notify("Cannot Download.Please try again"); }
🌐
GitHub
gist.github.com › stormwild › b8d6c4c5bebc7afc0e76074e397b692a
react-dotnet-core-axios-file-upload-and-download.md · GitHub
April 10, 2020 - Download ZIP · Raw · react-dotnet-core-axios-file-upload-and-download.md ·
🌐
Syncfusion
syncfusion.com › forums › 169241 › zip-file-corrupted-when-downloading-in-react-and-nodejs
Zip file corrupted when downloa... | React - EJ 2 Forums | Syncfusion®
November 10, 2017 - The file gets downloaded it shows 14kb so it contains something but when I try to open it says corrupted. Here is the React function that makes the download: iaId2() { var id = document.getElementById("id_desc").value; console.log(id); const article = { id_trimis:id} axios({url:"http://localhost:3001/descarcare", data:article, method:"POST", responseType: 'blob', }).then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.rel='nofollow' href = url; link.setAttribute('download', 'file.rar'); document.body.appendChild(link); link.click(); });
🌐
GitHub
github.com › axios › axios › issues › 2548
ZIP file corrupted . Using Axios POST method . · Issue #2548 · axios/axios
November 13, 2019 - let postZipData = { customerNumber: this.state.customerNumber, docList: this.state.docList, } const token = localStorage.getItem('token'); const axiosConfig = { responseType: 'arraybuffer', header: { 'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*', 'Authorization': 'Bearer ' + token } }; axios.post(SERVER_URL + '/api/user/bills/zip', postZipData, axiosConfig) .then((response) => { const url = new Blob([response.data],{ type:'application/zip' }); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'file.zip'); document.body.appendChild(link); link.click(); }) console.log('get the zip') }`
Author   gmumdzhiev
🌐
Futurestud.io
futurestud.io › tutorials › download-files-images-with-axios-in-node-js
Axios — Download Files & Images in Node.js - Future Studio
February 22, 2018 - It’s for illustration purposes and an image is visually appealing because you can look at it when opening the file on your hard disc. Alright, you have a sample image and the related download URL. Let’s implement the actual download functionality. The Axios initialization to request a file is equal to a request that expects another response payload format, like JSON.
🌐
YouTube
youtube.com › watch
Resolving Invalid File Issue When Downloading Zip File from Axios in React - YouTube
Learn how to properly download zip files using Axios in your React application, ensuring the file is valid and easy to extract.---This video is based on the ...
Published   November 25, 2025
Views   10
🌐
Nesin
nesin.io › blog › download-file-axios
How to Download any file using Axios - Nesin.io
March 5, 2023 - import axios from 'axios'; import fs from 'fs/promises'; async function main() { try { const downloadLink = 'https://example.com/test.pdf' const response = await axios.get(downloadLink, { responseType: 'arraybuffer' }); const fileData = Buffer.from(response.data, 'binary'); await fs.writeFile('./file.pdf', fileData); console.log('PDF file saved!'); } catch (err) { console.error(err); } } main();