如何将 Base64 字符串转换为 javascript 文件对象,如文件输入表单?
我想将从文件中提取的 Base64String(例如:AAAAA....~")转换为 javascript 文件对象.
I want to convert Base64String extracted from file(ex: "AAAAA....~") to a javascript file object.
我的意思的javascript文件对象是这样的代码:
The javascript file object what I mean is like this code:
HTML:
<input type="file" id="selectFile" >
JS:
$('#selectFile').on('change', function(e) {
var file = e.target.files[0];
console.log(file)
}
'file' 变量是一个 javascript 文件对象.所以我想像这样将base64字符串转换为javascript文件对象.
'file' variable is a javascript file object. So I want to convert a base64 string to the javascript file object like that.
我只想通过解码base64字符串(由其他应用程序从文件中编码)来获取文件对象,而不需要html文件输入表单.
I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form.
谢谢.
推荐答案
方式一:只适用于dataURL,不适用于其他类型的url.
Way 1: only works for dataURL, not for other types of url.
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});
}
//Usage example:
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');
console.log(file);
方式 2: 适用于任何类型的 url,(http url、dataURL、blobURL 等...)
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
//Usage example:
urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')
.then(function(file){ console.log(file);});
相关文章