这是一个代码片段,我想做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文件如在上面的代码?


当前回答

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
(async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();

or

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))

查看Response的构造函数,你可以将[blob,缓冲区源表单数据,可读流等]转换为Response,然后可以通过async方法/回调转换为[json,文本,数组缓冲区,blob]。

编辑:正如@Ralph所提到的,将所有内容转换为utf-8字符串会导致问题(不幸的是响应API没有提供转换为二进制字符串的方法),因此使用数组缓冲区作为中间,这需要更多的两个步骤(将其转换为字节数组,然后转换为二进制字符串),如果你坚持使用本机btoa方法。

其他回答

这招对我很管用:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(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 audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
     base64data = reader.result;
     console.log(base64data);
}
function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
(async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();

or

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))

查看Response的构造函数,你可以将[blob,缓冲区源表单数据,可读流等]转换为Response,然后可以通过async方法/回调转换为[json,文本,数组缓冲区,blob]。

编辑:正如@Ralph所提到的,将所有内容转换为utf-8字符串会导致问题(不幸的是响应API没有提供转换为二进制字符串的方法),因此使用数组缓冲区作为中间,这需要更多的两个步骤(将其转换为字节数组,然后转换为二进制字符串),如果你坚持使用本机btoa方法。

也许我遗漏了什么,但是

let encoded = btoa(await myblob.text());

... 是所有你需要做的编码一个Blob的数据到base64。参见Blob.text()和btoa()。

或者如果你想把所有事情都当做承诺

let encode = myblob.text().then(btoa);

PS:解码回一个Blob: new Blob([atob(encoded)])