如何将Base64字符串转换为javascript文件对象,如从文件输入表单?

时间:2016-03-11 12:27:23

标签: javascript html forms file base64

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

我的意思是javascript文件对象就像这段代码:

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文件对象。

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

谢谢。

5 个答案:

答案 0 :(得分:50)

方式1:仅适用于dataURL,不适用于其他类型的网址。

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:适用于任何类型的网址,(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);
})

答案 1 :(得分:20)

const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name")
  })

Base64字符串 - &gt; Blob - &gt;文件。

答案 2 :(得分:5)

这是最新的async/await模式解决方案。

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

答案 3 :(得分:0)

抬头,

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

    <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" 
onchange="readMtlAtClient()" accept=".mtl"/>

然后mtlFileContent将您的文本作为已解码的字符串!

答案 4 :(得分:0)

我有一个非常相似的要求(从外部xml导入文件导入base64编码的图像。使用xml2json-light library转换为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});

我的传入json对象在通过xml2json-light转换后具有两个属性:FileName和_ @ ttribute(传入元素的主体中包含的b64图像数据。)我需要根据传入的对象生成mime类型。文件名扩展名。一旦我从json对象中提取/引用了所有片段,生成一个新File对象的简单任务(使用cuixiping提供的代码参考)就可以与我现有的类完全兼容,该类期望从浏览器元素生成一个文件对象

希望这有助于将其他点连接起来。