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

谢谢.

推荐答案

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

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

Html相关问答推荐

为什么在这种情况下是弹性基础:自动不解决内容的大小?

我的表的第一列似乎是推其他2列到右边,我不能改变它

正文不能填满浏览器100%的高度

类型';联系人组件';上不存在属性';name FormControl';

如何将功能附加到嵌入式药剂中的按钮?

如何显示自定义按钮以将产品添加到WooCommerce购物车?

为什么要添加换行符(至少在 Google Chrome 中)

太多的 Web 视图实例导致手机过热 Swift

margin-top 未应用于无序列表的第一项

将三个div转换为显示flex

并排对齐两个文本区域列

白色栏超出页面100%的右侧

CSS "overflow"不能显示整个单词

当悬停时,同时影响相邻的两侧div

CSS 字母间距将按钮向右扩展

如何让一个 div 始终贴在容器的边缘?

暗模式转换器

Primeng浮动标签溢出管理

本地 css 样式表未链接

标题之间和之后的 Hr 线