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?
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.
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 !
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 });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With