Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download binary file with Axios

For example, downloading of PDF file:

axios.get('/file.pdf', {
      responseType: 'arraybuffer',
      headers: {
        'Accept': 'application/pdf'
      }
}).then(response => {
    const blob = new Blob([response.data], {
      type: 'application/pdf',
    });
    FileSaver.saveAs(blob, 'file.pdf');
});

The contend of downloaded file is:

[object Object]

What is wrong here? Why binary data not saving to file?

like image 868
Anton Pelykh Avatar asked Feb 28 '18 23:02

Anton Pelykh


People also ask

How do I download images from Axios?

Implement the Axios File Download in Node. js. The Axios initialization to request a file is equal to a request that expects another response payload format, like JSON. To download a file, explicitly define responseType: 'stream' as a request option.


2 Answers

I was able to create a workable gist (without using FileSaver) as below:

axios.get("http://my-server:8080/reports/my-sample-report/",
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/pdf'
            }
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error));

Hope it helps.

Cheers !

like image 103
Nayab Siddiqui Avatar answered Oct 10 '22 05:10

Nayab Siddiqui


I was able to download a tgz file based on Nayab Siddiqui answer.

const fsPromises = require('fs').promises;
const axios = require('axios'); 

await axios.get('http://myServer/myFile.tgz',
        {
            responseType: 'arraybuffer', // Important
            headers: {
                'Content-Type': 'application/gzip'
            }
        })
        .then(async response => {
            await fsPromises.writeFile(__dirname + '/myFile.tgz', response.data, { encoding: 'binary' });
        })
        .catch(error => {
            console.log({ error });
        });
like image 29
Shmulik Kreitenberger Avatar answered Oct 10 '22 05:10

Shmulik Kreitenberger