[英]Download binary file with Axios
例如下載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');
});
下載文件的內容為:
[object Object]
這里有什么問題? 為什么二進制數據不保存到文件?
我能夠創建一個可行的要點(不使用 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));
希望它有幫助。
干杯!
我能夠根據 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 });
});
看起來 response.data 只是一個普通對象。 Blob 接受它們的第一個參數“一個由 ArrayBuffer、ArrayBufferView、Blob 或 DOMString 對象組成的數組”。
嘗試將其包裝在 JSON.stringify 中
const blob = new Blob([JSON.stringify(response.data)]
那么它將滿足 DOMString 要求。
這種方法可能對將來尋找答案的人有所幫助。
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.