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

问题描述 投票:2回答:2

我有一个图像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 Type对象。

: 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: ""
node.js reactjs fileapi
2个回答
0
投票

将图像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 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)
   })

0
投票

我假设您想在浏览器环境中运行它。您可以使用本机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
  })
© www.soinside.com 2019 - 2024. All rights reserved.