使用Fetch API下载图片 [英] Download Image using Fetch API

查看:526
本文介绍了使用Fetch API下载图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经回答了,但是使用Fetch API下载图像时遇到了问题.
我用来获取图像的代码.

function downloadImage() {
  fetch('https://upload.wikimedia.org/wikipedia/commons/9/98/Pet_dog_fetching_sticks_in_Wales-3April2010.jpg',
    {mode: 'no-cors'})
  .then(response => response.blob())
  .then(blob => {
        console.log(blob);           
  });
}

在这里,当我执行console.log时,我会得到响应Blob {size: 0, type: ""}.
请让我知道我在做什么错了吗?

解决方案

默认情况下,抓取使用CORS模式.但是,当服务器响应不包含"Access-Control-Allow-Origin"标头时.跳过响应正文.

具有讽刺意味的是,您必须将模式设置为"no-cors" 请求不透明的资源.不透明的响应 无法通过JavaScript访问,但是响应仍可以由服务人员提供或缓存.

https://developers.google.com/web/ilt/pwa/with-the-fetch-api

I know this question is answered, but I am facing issue while downloading image using Fetch API.
Code that I am using to get image.

function downloadImage() {
  fetch('https://upload.wikimedia.org/wikipedia/commons/9/98/Pet_dog_fetching_sticks_in_Wales-3April2010.jpg',
    {mode: 'no-cors'})
  .then(response => response.blob())
  .then(blob => {
        console.log(blob);           
  });
}

Here, when I do console.log I get response Blob {size: 0, type: ""}.
Please let me know what I am doing wrong here?

解决方案

By default fetch uses CORS mode. But when server response doesn't contain 'Access-Control-Allow-Origin' header. It skips response body.

Ironically, you have to set mode as 'no-cors' to request opaque resources. Opaque responses can't be accessed with JavaScript but the response can still be served or cached by a service worker.

https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

这篇关于使用Fetch API下载图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆