简体   繁体   English

将 Base64 图像文件 URI 转换为文件 Object

[英]Convert Base64 Image File URI to a File Object

I have to send the File object as payload to the backend API.我必须将File object 作为有效负载发送到后端 API。 How can I convert a Base64 Image File URI to a File object format as mentioned below?如何将 Base64 图像文件 URI 转换为文件 object 格式,如下所述? I tried to look up for other solutions but those are with Blob to file conversion or base64 data url conversion.我试图寻找其他解决方案,但那些是 Blob 到文件转换或 base64 数据 url 转换。 Could anyone please help?有人可以帮忙吗?

Base64 Image File URL Base64 图像文件 URL

data:image/jpeg;base64,file:///storage/emulated/0/Android/data/com.abc/cache/1586842420784.jpg

This needs to be converted to这需要转换为

File Object文件 Object

File {
   lastModified: 1582829787565
   lastModifiedDate: Thu Feb 27 2020 10:56:27 GMT-0800 (Pacific Standard Time) {}
   name: "TestImageAM.png"
   size: 186278
   type: "image/png"
   webkitRelativePath: ""
}

Personally I think the best option would be converting the base64 image string to a blob like this我个人认为最好的选择是将 base64 图像字符串转换为这样的 blob

    fetch(base64ImageString)
    .then((res) => res.blob())
    .then((blob) => {
      console.log(blob);
    });

Which logs the blob object to the console like below它将 blob object 记录到控制台,如下所示

Blob {size: 20832, type: "image/jpeg"}

And then upload the image using formData which supports uploading image files in blob format like this.然后使用 formData 上传图像,它支持像这样以 blob 格式上传图像文件。

var formData = new FormData();
formData.append('my_image', blob);

You can get more information regarding how to upload images using formData from the documentation here .您可以从此处的文档中获取有关如何使用 formData 上传图像的更多信息。

All you need to do is, pass the Base64 Image URI to JavaScript's File constructor and that should give you the File object in your required format.您需要做的就是将 Base64 Image URI 传递给JavaScript 的File构造函数,这应该会为您提供所需格式的 File object。

fileURI = 'data:image/jpeg;base64,file:///storage/emulated/0/Android/data/com.abc/cache/1586842420784.jpg'
const file = new File(fileURI, 'anyname.jpg')
console.log('File Object', file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM