如何将Base64字符串转换为JavaScript文件对象,如从文件输入形式? [英] How to convert Base64 String to javascript file object like as from file input form?

查看:133
本文介绍了如何将Base64字符串转换为JavaScript文件对象,如从文件输入形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将从文件中提取的Base64String(例如:AAAAA ....〜)转换为javascript文件对象。

javascript文件对象意思是这样的代码:



HTML:

 < input type =fileid =selectFile> 

JS:

 < code $('#selectFile')。on('change',function(e){
var file = e.target.files [0];

console。日志(文件)
}



变量是一个JavaScript文件对象。希望将base64字符串转换为javascript文件对象。



我只想通过解码base64字符串(由其他应用程序从文件编码)获取文件对象,而无需html文件输入表单。



谢谢。

解决方案

方式1:只适用于dataURL,不适用于其他类型的url。



$ p $ function dataURLtoFile(dataurl,filename ){
var arr = dataurl.split(','),mime = arr [0] .match(/:(。*?); /)[1],
bstr = atob(arr [n]); n = bstr.length,u8arr = new Uint8Array(n);
while(n - ){
u8arr [n] = bstr.charCodeAt(n);
}
返回新文件([u8arr],文件名,{ty例如:
var file = dataURLtoFile('data:text / plain; base64,aGVsbG8gd29ybGQ =','hello.txt );
console.log(file);

方式2:适用于任何类型的网址(http url, dataURL,blobURL等)

  //返回一个用File实例解析的promise 
function urltoFile (函数(buf))(函数(res){返回res.arrayBuffer();})
.then(函数(buf) {return new File([buf],filename,{type:mimeType});})
);
}

//用法示例:
urltoFile('data:text / plain; base64,aGVsbG8gd29ybGQ =','hello.txt','text / plain')
.then(函数(文件){
console.log(文件);
})


I want to convert Base64String extracted from file(ex: "AAAAA....~") to a javascript file object.

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' variable is a javascript file object. So I want to convert a base64 string to the javascript file object like that.

I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form.

Thank you.

解决方案

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);

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

这篇关于如何将Base64字符串转换为JavaScript文件对象,如从文件输入形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆