最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download Image using Fetch API - Stack Overflow

programmeradmin1浏览0评论

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('.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?

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?

Share Improve this question edited Oct 15, 2017 at 3:31 sideshowbarker 88k29 gold badges214 silver badges211 bronze badges asked Oct 9, 2017 at 8:05 Tavish AggarwalTavish Aggarwal 1,0603 gold badges23 silver badges53 bronze badges 12
  • 2 You should use {mode: 'cors'}. – R Lam Commented Oct 9, 2017 at 8:20
  • With it I am getting error: No 'Access-Control-Allow-Origin' header is present on the requested resource.If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. – Tavish Aggarwal Commented Oct 9, 2017 at 8:25
  • 1 @TavishAggarwal Are you fetching wikimedia images ? Because they definitely have CORS headers and this code will definitely work. If you want to fetch some other 3rd party resources, then it's not possible without those headers. – user2652134 Commented Oct 9, 2017 at 8:31
  • 1 Yes, @BrahmaDev.. I am fetching third party images with mode {mode: 'no-cors'}. But am getting empty object. – Tavish Aggarwal Commented Oct 9, 2017 at 8:33
  • 1 @Kaiido - perhaps I did – Jaromanda X Commented Oct 15, 2017 at 5:52
 |  Show 7 more comments

1 Answer 1

Reset to default 15

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

发布评论

评论列表(0)

  1. 暂无评论