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?
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 !
It looks like response.data is just a regular object. Blobs take in their first argument "an Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects."
Try wrapping it in JSON.stringify
const blob = new Blob([JSON.stringify(response.data)]
Then it will satisfy the DOMString requirement.
来源:https://stackoverflow.com/questions/49040247/download-binary-file-with-axios