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

Node.js 如何将图像源转换为JavaScript文件对象,node.js,reactjs,fileapi,Node.js,Reactjs,Fileapi,我有一个图像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:0

我有一个图像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: ""

我假设您希望在浏览器环境中运行此功能。 您可以使用本机
fetch()
方法,将响应读取为
Blob
,并将其转换为
文件
对象

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

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

consturl='1〕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'
常量文件名='myFile.jpg'
获取(url)
。然后(异步响应=>{
const contentType=response.headers.get('content-type')
const blob=wait response.blob()
const file=新文件([blob],文件名,{contentType})
//在这里访问文件
})

将图像转换为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
文件
对象

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

对不起,我不明白。您有一个指向图像的路径。好啊你想用这条路做什么?或者用图像。“将其转换为文件类型”对我来说毫无意义。@Torf我认为OP希望以浏览器
文件
object@Torf,我想将图像源转换为浏览器
文件
对象可能已在此处回答: