如何将后端给的图片文件以Blob形式保存在内存呢?

背景:

后端提供了一个接口来下载图片: /api/download?code=XXX , 用法是使用Get请求,参数配置上一个code,就能下载图片。

问题:

(1)我想通过 fetch(url) 的方式下载下来保存到内存里,但浏览器提示我跨域了,不知道怎么处理了
(2)如果上面下载成功了的话,怎么将图片转成blob的格式呢

(PS:跨域问题只能由我解决,后端不是我们部门的后端)

十分感谢~

阅读 2.7k
1 个回答

跨域的问题 用代理转发就行了。
开发环境用 devServer.proxy
正式环境用 Nginx 代理就好了

fetch 下载 blob

fetch('url', {
    method: 'GET',
    headers: {
        responseType: 'blob',
    },
})
    .then((res) => res.blob())
    .then((res) => {
        console.log(res)
    })
//--------------------or-------------------
fetch('url', {
    method: 'GET',
    headers: {
        responseType: 'arraybuffer',
    },
})
    .then((res) => res.arrayBuffer())
    .then((res) => {
        const blob = new Blob([res])
        console.log(blob)
    })
推荐问题