[英]Convert url to file object with JavaScript
I have converted an image into dataurl
using FileReader
and it gives me output like: 我已经使用
FileReader
将图像转换为dataurl
,它给出了如下输出:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBl…Vp1m8u4+SV/s0TpD8+91R/3Xlf8sXZv9Y9OGLk5eyVnCNu19Ntdu2jYOnaHtG7ffb7t/uP/9k=
Which is a very long string.. 这是一个非常长的字符串..
Now I again want to convert it to file object so that I can post this image. 现在我再次想将它转换为文件对象,以便我可以发布此图像。
How can I again convert this image into file object 如何再次将此图像转换为文件对象
Converting dataurl
to File Object 将
dataurl
转换为File对象
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], { type: 'image/jpeg' });
var file = new File([blob], "image.jpg");
based on @William-t answer / more discussion on stackoverflow.com/questions/4998908/ 基于@ William-t回答/关于stackoverflow.com/questions/4998908/的更多讨论
A Blob object represents a file-like object of immutable, raw data.
Blob对象表示不可变的原始数据的类文件对象。 Blobs represent data that isn't necessarily in a JavaScript-native format.
Blob表示不一定采用JavaScript本机格式的数据。 The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
File接口基于Blob,继承blob功能并将其扩展为支持用户系统上的文件。
var form = new FormData(),
request = new XMLHttpRequest();
form.append("image", blob, "myimage.jpg");
request.open("POST", "/upload", true);
request.send(form);
You can use fetch to convert an url to a File object. 您可以使用fetch将url转换为File对象。
//load src and convert to a File instance object
//work for any type of src, not only image src.
//return a promise that resolves with a File instance
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
}
//usage example: (works in Chrome and Firefox)
srcToFile(
'data:image/gif;base64,R0lGODlhDgANAKIAAAAAAP///9HV2U5RU////wAAAAAAAA'
+ 'AAACH5BAEAAAQALAAAAAAOAA0AAAMXSLrc/hCO0Wa1atJLtdTbF0ZjZJ5oyiQAOw==',
'arrow.gif',
'image/gif'
)
.then(function(file){
console.log(file);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.