弄了半天,转换来转换去,就是转换不对,没有弄明白。
比如:
export async function downloadPikachu(): Promise<Blob | undefined> {
const options: AxiosRequestConfig = {
method: "GET",
// url: "https://static.wikia.nocookie.net/villainstournament/images/8/89/Pikachu.jpg/revision/latest?cb=20190528172002",
url: "https://static.wikia.nocookie.net/villainstournament/images/8/89/Pikachu.jpg",
headers: {}
};
try {
const res = await axios(options);
if (res.status === 200) {
console.log(res);
// TODO:
// const arrBuffer = res.data as ArrayBuffer;
// const int8Array = Array.from(new Uint8Array(arrBuffer));
// const blob = new Blob([arrBuffer], { type: "application/octet-stream" });
// const blob = new Blob([new Uint8Array(int8Array)]);
// return blob;
}
return undefined;
} catch (error) {
console.log(error);
return undefined;
}
}
p.s. 需要 Blob ,是因为后面还要用(这样 chrome 就能够根据 blob 下载文件了,相当于 save as 成一个文件)
const urlFile = window.URL.createObjectURL(blobData);
const a = document.createElement("a");
document.body.appendChild(a);
a.href = urlFile;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(urlFile);
a.remove();
1
FaiChou 2022-03-06 22:32:40 +08:00
|
2
moen 2022-03-06 22:32:57 +08:00
fetch 直接调用 Response.blob(),而 axios 要在 Request Config 设置 responseType 为 blob
|
3
yazoox OP @moen 试过了,不行呢。
axios 设置了 headers: { responseType: "blob" } 没有用呢。取回来的结果 res.data ,和不添加这个 header 是一样的。 而且,window.URL.createObjectURL(blobData); 会出错, “Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.” |
4
Puteulanus 2022-03-07 00:20:52 +08:00
@yazoox responseType 不是放在 headers 里的,跟 method 那些放在同一层
createObjectURL 和下面那一堆可以看看 https://github.com/eligrey/FileSaver.js |
5
Juszoe 2022-03-07 00:28:09 +08:00
```
const r = await axios.get(url, { responseType: "blob", }); const urlFile = window.URL.createObjectURL(new Blob([r.data])); const a = document.createElement("a"); a.href = urlFile; a.download = fileName; document.body.appendChild(a); link.click(); ``` 我这段代码运行正常,responseType 不是在 headers 里设置哦 |
6
yazoox OP |