javascript 使用 Axios 下载二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49040247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download binary file with Axios
提问by Anton Pelykh
For example, downloading of PDF file:
例如,下载PDF文件:
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?
这里有什么问题?为什么二进制数据不保存到文件?
回答by Nayab Siddiqui
I was able to create a workable gist (without using FileSaver) as below:
我能够创建一个可行的要点(不使用 FileSaver),如下所示:
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 !
干杯!
回答by maxLatoche
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."
看起来 response.data 只是一个普通对象。Blob 接受它们的第一个参数“一个由 ArrayBuffer、ArrayBufferView、Blob 或 DOMString 对象组成的数组”。
Try wrapping it in JSON.stringify
尝试将其包装在 JSON.stringify 中
const blob = new Blob([JSON.stringify(response.data)]
Then it will satisfy the DOMString requirement.
那么它将满足 DOMString 要求。
回答by zensine
Nova.request().get(`api`,{responseType: 'arraybuffer'})
.then(response => {
console.log("sa", response)
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', file_name)
document.body.appendChild(link)
link.click()
});
i am using like dis but when i download i getting as as photo source file is missing
我正在使用类似的 dis 但是当我下载时,我发现缺少照片源文件

