如何将图像源转换为JavaScript文件对象

16

我有一个图片URL:"https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg",希望将其转换为JavaScript文件类型对象。

: File
   lastModified: 1591250106736
   lastModifiedDate: Thu Jun 04 2020 11:25:06 GMT+0530 (India Standard 
   Time) {}
   name: "7.jpeg"
   size: 369742
   type: "image/jpeg"
   webkitRelativePath: ""

抱歉,我不太明白。你有一张图片的路径。好的。你想用这个路径做什么?或者是想对这张图片做什么操作?“将其转换为文件类型”对我来说没有意义。 - Torf
1
@Torf 我认为 OP 想要将文件作为浏览器的 File 对象获取。 - thammada.ts
@Torf,我想将图像源转换为浏览器的“文件”对象。 - Kumar
1
也许这个问题已经在这里得到了解答:https://dev59.com/BFcQ5IYBdhLWcg3wFP2a - Torf
4个回答

23

将您的图像 src https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg 转换为 Base64 URL 格式,然后将 Base64 URL 转换为 JavaScript File 对象。

***Here is the code for converting "image source" (url) to "Base64".***

let url = 'https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg'
const toDataURL = url => fetch(url)
      .then(response => response.blob())
      .then(blob => new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onloadend = () => resolve(reader.result)
      reader.onerror = reject
      reader.readAsDataURL(blob)
     }))


***Here is code for converting "Base64" to javascript "File Object".***

  function dataURLtoFile(dataurl, filename) {
     var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
     while(n--){
     u8arr[n] = bstr.charCodeAt(n);
     }
   return new File([u8arr], filename, {type:mime});
  }


*** Calling both function ***

  toDataURL(url)
  .then(dataUrl => {
     console.log('Here is Base64 Url', dataUrl)
     var fileData = dataURLtoFile(dataUrl, "imageName.jpg");
     console.log("Here is JavaScript File Object",fileData)
     fileArr.push(fileData)
   })

14

我假设您想在浏览器环境下运行此代码。

您可以使用原生的fetch()方法,将响应读取为Blob并将其转换为File对象。

contentType应该基于实际下载的图像类型。

您可以在这里了解更多关于将Blob转换为File的几种方法和浏览器支持:

将Blob转换为File

如何在JavaScript中将Blob转换为File

const url = 'https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg?v=1572867553'
const fileName = 'myFile.jpg'

fetch(url)
  .then(async response => {
    const contentType = response.headers.get('content-type')
    const blob = await response.blob()
    const file = new File([blob], fileName, { contentType })
    // access file here
  })

有没有关于如何为File对象附加临时路径的任何指针? - Satonamo
@thammada.ts 当我使用它时,文件类型是text/html,链接是图像.. 有什么解决办法吗?谢谢 - user10033434
@user10033434 内容类型由目标服务器发送。你正在获取的链接可能在头部返回了错误的类型。如果你确定内容类型,可以使用固定值,例如 contentType: 'image/jpeg'contentType: 'image/png' - thammada.ts

9

为了得到更优雅的解决方案,请使用以下内容

const getUrlExtension = (url) => {
    return url
      .split(/[#?]/)[0]
      .split(".")
      .pop()
      .trim();
  }

const onImageEdit = async (imgUrl) => {
    var imgExt = getUrlExtension(imgUrl);

    const response = await fetch(imgUrl);
    const blob = await response.blob();
    const file = new File([blob], "profileImage." + imgExt, {
      type: blob.type,
    });
}

当我给AWS S3上图像的URL时,收到了“无法获取”的消息。为什么会这样?在浏览器中可以看到该图像。 - user10033434

1
@Alphapico的回答非常有效,只需要返回文件即可。
const onImageEdit = async (imgUrl) => {
    var imgExt = getUrlExtension(imgUrl);

    const response = await fetch(imgUrl);
    const blob = await response.blob();
    const file = new File([blob], "profileImage." + imgExt, {
      type: blob.type,
    });
    
    return file;

}

可能是情况各异的情况

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接