将图像 url 转换为文件 JavaScript

Convert image url to file JavaScript

为什么我无法转换 png url?与 jpg 效果很好

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))

在这个特定示例中,pngimg.com 似乎不允许 CORS。

而 picsum.photos 是。例如工作正常。

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))

我找不到托管 png 并允许 CORS 的来源。但是上面的例子使用 webp 来证明它不是真正的 PNG 问题。

更新

正如@KiwiKilian 发布的 png 图片 URL,它似乎工作正常。例如

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

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

问题不在于文件类型,而在于 pngimg.com 服务器的 CORS 配置。他们的服务器基本上不允许您从另一个域访问他们的资源。摘自 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.

此 png 将适用于您的代码:https://dummyimage.com/420x320/ff7f7f/333333.png&text=Sample