Download binary file with Axios
51,965
Solution 1
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 !
Solution 2
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 });
});
Author by
Anton Pelykh
Backend development is that I really enjoy :) and DevOps a little bit...
Updated on September 13, 2021Comments
-
Anton Pelykh over 2 years
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?
-
Nayab Siddiqui almost 6 yearsThanks. Glad I could help. Cheers !
-
Right leg over 5 yearsThanks,
responseType: 'arraybuffer'
was what I missed. -
Daniel Elkington about 5 years
responseType: 'arraybuffer'
is the solution -
tonysepia about 4 yearsThis has also helped me serve Microsoft Office files, so your post is universally helpful!
-
Cihangir Bozdogan almost 4 yearsOMG. You are absolute life saver. I knew this snippet will work even before i paste it.
-
AbingPj almost 4 yearsThank you so much,. its works but how can i pass data or request with data to the server?
-
SeyyedKhandon about 3 yearsHow can we cancel the started download?
-
AR Second about 3 years@Nayab Siddiqui- could you please answer this question, Thanks --- stackoverflow.com/questions/67065615/…
-
Nilupul Heshan about 2 yearshow can I display pdf in browser
-
M.K. Malik about 2 yearsworking but the file size is in bytes. file is not downloading completely, it's currupted