首页 > 解决方案 > 如何使用远程 url 从 img 标签中检索图像并从中创建 File 对象

问题描述

脚步:

我有一个远程图片网址。

我从中生成了 img 标签。

现在我想读取这个 img 标签并将其转换为 File 对象,以便我可以将其发送到服务器进行上传。

方法一尝试:我已经尝试过fetch方法,直接尝试从远程url获取图片数据。

方法2试过:

clicked = () => {
const img = document.getElementById('someId');

const options = {
  method: 'get',
  headers: {
    'Access-Control-Request-Headers': '*',
    'Access-Control-Request-Method': '*',
  },
  mode: 'cors',
};

fetch(img.src, options)
  .then(res => res.blob())
  .then((blob) => {
    const file = new File([blob], 'dot.png', blob);
    console.log(file);
  });
}

预期的输出是 File 对象。

标签: javascriptreactjs

解决方案


我在这里使用 axios 但主体应该相同:

const res = await axios.get(`/api/image/${imageId}`, {
responseType: 'arraybuffer'
});
const imgFile = new Blob([res.data]);
const imgUrl = URL.createObjectURL(imgFile);

忽略响应类型。


推荐阅读