这是一个代码片段,我想做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文件如在上面的代码?
我想要的东西,我可以访问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的内容
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。
如果你的“blob”是一个实际的blob对象,而不是一个blob url,转换非常简单:
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = () => resolve(reader.result)
Blob对象示例:
console.log(blob)
输出:
Blob {lastModified: 1658039931443, lastModifiedDate: Sun Jul 17 2022 08:38:51 GMT+0200 (Central European Summer Time), name: '1.jpg', size: 35493, type: 'image/jpeg'}
lastModified: 1658039931443
lastModifiedDate: Sun Jul 17 2022 08:38:51 GMT+0200 (Central European Summer Time) {}
name: "1.jpg"
size: 35493
type: "image/jpeg"
[[Prototype]]: Blob
在我的例子中,这个blob是由Compressorjs生成的(如果你需要图像压缩)。