如何将 Base64 字符串转换为 javascript 文件对象,就像从文件输入表单一样?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35940290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Base64 String to javascript file object like as from file input form?
提问by Dayamre
I want to convert Base64String extracted from file(ex: "AAAAA....~") to a javascript file object.
我想将从文件中提取的 Base64String(例如:“AAAAA....~”)转换为 javascript 文件对象。
The javascript file object what I mean is like this code:
javascript文件对象我的意思是这样的代码:
HTML:
HTML:
<input type="file" id="selectFile" >
JS:
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.
'file' 变量是一个 javascript 文件对象。所以我想将 base64 字符串转换为这样的 javascript 文件对象。
I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form.
我只想通过解码 base64 字符串(由文件中的其他应用程序编码)来获取文件对象,而无需 html 文件输入表单。
Thank you.
谢谢你。
回答by cuixiping
Way 1:only works for dataURL, not for other types of url.
方式一:只适用于dataURL,不适用于其他类型的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...)
方式 2:适用于任何类型的 url,(http url、dataURL、blobURL 等...)
//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);});
回答by Preethi Kumar
const url = 'data:image/png;base6....';
fetch(url)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name",{ type: "image/png" })
})
Base64 String -> Blob -> File.
Base64 字符串 -> Blob -> 文件。
回答by JHBSA
I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light libraryto convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.
我有一个非常相似的要求(从外部 xml 导入文件导入 base64 编码的图像。使用xml2json-light 库转换为 json 对象后,我能够利用上面 cuixiping 的答案的见解将传入的 b64 编码图像转换为一个文件对象。
const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});
My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.
我传入的 json 对象在通过 xml2json-light 转换后有两个属性:FileName 和 _@ttribute(这是包含在传入元素主体中的 b64 图像数据。)我需要根据传入的 FileName 扩展名生成 mime-type。一旦我从 json 对象中提取/引用了所有部分,这是一项简单的任务(使用 cuixiping 提供的代码引用)生成新的 File 对象,该对象与我现有的类完全兼容,该类期望从浏览器元素生成文件对象.
Hope this helps connects the dots for others.
希望这有助于为其他人连接点。
回答by jimver04
Heads up,
当心,
JAVASCRIPT
爪哇脚本
<script>
function readMtlAtClient(){
mtlFileContent = '';
var mtlFile = document.getElementById('mtlFileInput').files[0];
var readerMTL = new FileReader();
// Closure to capture the file information.
readerMTL.onload = (function(reader) {
return function() {
mtlFileContent = reader.result;
mtlFileContent = mtlFileContent.replace('data:;base64,', '');
mtlFileContent = window.atob(mtlFileContent);
};
})(readerMTL);
readerMTL.readAsDataURL(mtlFile);
}
</script>
HTML
HTML
<input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput"
onchange="readMtlAtClient()" accept=".mtl"/>
Then mtlFileContent has your text as a decoded string !
然后 mtlFileContent 将您的文本作为解码字符串!