【问题标题】:How to convert image source into a JavaScript File object如何将图像源转换为 JavaScript File 对象
【发布时间】:2020-09-22 13:19:10
【问题描述】:

我有一个图像 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 我认为OP希望将文件作为浏览器File object
  • @Torf,我想把图片源转换成浏览器Fileobject
  • 也许这里已经回答了:stackoverflow.com/questions/43358456/…

标签: node.js reactjs fileapi


【解决方案1】:

将您的图像 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 ULR 格式,然后将 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)
   })

【讨论】:

    【解决方案2】:

    我假设您想在浏览器环境中运行它。 您可以使用原生的fetch() 方法,将响应读取为Blob 并将其转换为File 对象。

    contentType应根据实际下载的图片类型而定。

    您可以在此处阅读有关将Blob 转换为File 的多种方法和浏览器支持的更多信息:

    Convert blob to file

    How to convert Blob to File in JavaScript

    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 对象附加临时路径的任何指针?
    【解决方案3】:

    要获得更优雅的解决方案,请使用此

    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,
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-25
      • 2017-10-20
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2016-02-14
      • 2021-08-31
      • 2021-08-05
      相关资源
      最近更新 更多