请教下,通过 fetch/axios 从网上 GET 到的文件, response.data 是 ArrayBuffer 还是 Blob,怎么转换呀?

2022-03-06 22:26:24 +08:00
 yazoox

弄了半天,转换来转换去,就是转换不对,没有弄明白。

比如:

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();
2115 次点击
所在节点    JavaScript
6 条回复
FaiChou
2022-03-06 22:32:40 +08:00
if (res.status === 200) { return res.blob(); }

http://danml.com/download.html
moen
2022-03-06 22:32:57 +08:00
fetch 直接调用 Response.blob(),而 axios 要在 Request Config 设置 responseType 为 blob
yazoox
2022-03-06 23:06:10 +08:00
@moen 试过了,不行呢。
axios 设置了 headers: { responseType: "blob" } 没有用呢。取回来的结果 res.data ,和不添加这个 header 是一样的。
而且,window.URL.createObjectURL(blobData); 会出错,
“Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.”
Puteulanus
2022-03-07 00:20:52 +08:00
@yazoox responseType 不是放在 headers 里的,跟 method 那些放在同一层

createObjectURL 和下面那一堆可以看看 https://github.com/eligrey/FileSaver.js
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 里设置哦
yazoox
2022-03-07 08:45:01 +08:00
@Puteulanus
@Juszoe
...... 果然,真是好低级的错误
谢谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/838445

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX