[英]Download binary file with Axios
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?
为什么二进制数据不保存到文件?
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 !干杯!
I was able to download a tgz file based on Nayab Siddiqui answer.我能够根据 Nayab Siddiqui 的回答下载一个 tgz 文件。
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 });
});
It looks like response.data is just a regular object.看起来 response.data 只是一个普通对象。 Blobs take in their first argument "an Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects."
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 要求。
This approach might be helpful to someone looking for answer in the future.这种方法可能对将来寻找答案的人有所帮助。
var axios = require("axios");
const fs = require("fs");
var config = {
method: "get",
url: YOUR_REQUEST_URL,
responseType: "arraybuffer",
headers: {
//put your headers here if any required
},
};
axios(config)
.then(function (response) {
fs.writeFileSync("/path/to/file", Buffer.from(response.data));
})
.catch(function (error) {
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.