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

新手上路,请多包涵

我想将从文件中提取的 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文件输入表单。

谢谢你。

原文由 Dayamre 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
2 个回答

方式1: 仅适用于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);

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

原文由 cuixiping 发布,翻译遵循 CC BY-SA 4.0 许可协议

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 字符串 -> Blob -> 文件。

原文由 Preethi Kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题