这是一个代码片段,我想做Blob到Base64字符串:
这个注释部分可以工作,当它生成的URL被设置为img src时,它会显示图像:
var blob = items[i].getAsFile();
//var URLObj = window.URL || window.webkitURL;
//var source = URLObj.createObjectURL(blob);
//console.log("image source=" + source);
var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result)
}; // data url!
var source = reader.readAsBinaryString(blob);
问题在于较低的代码,生成的源变量为空
更新:
有一个更简单的方法来做到这一点与JQuery能够创建Base64字符串从Blob文件如在上面的代码?
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data);
}
将文档readAsDataURL编码为base64
作为一个可等待的函数:
function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
注意:如果不首先删除Base64编码数据之前的data - url声明,blob的结果不能直接解码为Base64。为了只检索Base64编码的字符串,首先从结果中删除data:/; Base64。
我想要的东西,我可以访问base64值存储到一个列表,为我添加事件监听器工作。您只需要FileReader,它将读取图像blob并在结果中返回base64。
createImageFromBlob(image: Blob) {
const reader = new FileReader();
const supportedImages = []; // you can also refer to some global variable
reader.addEventListener(
'load',
() => {
// reader.result will have the required base64 image
const base64data = reader.result;
supportedImages.push(base64data); // this can be a reference to global variable and store the value into that global list so as to use it in the other part
},
false
);
// The readAsDataURL method is used to read the contents of the specified Blob or File.
if (image) {
reader.readAsDataURL(image);
}
}
最后一部分是readAsDataURL,它非常重要,用于读取指定Blob的内容