把后端返回来的base64 code在前端javascrip中转换成File对象
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:image/png;base64,......', 'a.png');
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){
mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
console.log(file);
})
来源:https://stackoverflow.com/questions/16968945/convert-base64-png-data-to-javascript-file-objects
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/164147.html