简体   繁体   中英

Convert image url to file JavaScript

What the reason that I can't convert png url? With jpg works well

const getFileFromUrl = async (url, defaultType = 'image/jpeg') => {
    const response = await fetch(url);
    const data = await response.blob();

    return new File([data], url, {
      type: response.headers.get('content-type') || defaultType,
    });
  };

const pngUrl = 'https://pngimg.com/uploads/smoke/smoke_PNG55226.png';

const jpgUrl = 'picsum.photos/id/930/536/354.jpg';

getFileFromUrl(pngUrl).then(data => console.log(data)).catch(err => console.log(err))

The problem is not about the filetypes but the CORS configurations of the pngimg.com server. Their server basically doesn't allow you to access their resources from another domain. Taken from MDN :

The response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin.

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value.

This png will work fine with your code: https://dummyimage.com/420x320/ff7f7f/333333.png&text=Sample

In this particular example it seems like pngimg.com doesn't allow CORS.

While picsum.photos does. For example works fine.

webp = 'https://i.picsum.photos/id/294/200/300.webp?hmac=TfUv_Mk33Jmph_emWudbTWVO4e60vnZnJHp_f4emHEo'

getFileFromUrl(webp).then((d) => {
  console.log(d);
}).catch(err => console.log(err))

I couldn't find a source which hosts png and allows CORS. But above example uses webp to demonstrate that its not really PNG issue as such.

Update

As @KiwiKilian posted png image URL, it seems to be working just fine. For example

let png = 'https://dummyimage.com/420x320/ff7f7f/333333.png&text=Sample'

getFileFromUrl(png).then((d) => {
  console.log(d);
}).catch(err => console.log(err))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM