JavaScript如何将Blob转换为字符串并再次转换回去

8
我可以使用FileReader将Blob转换为字符串,但我想将其转换回来:
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
   base64data = reader.result;
   var blobToSend = base64data.substr(base64data.indexOf(',')+1);
   rtcMultiConnection.send({"command":{
       "recording":blobToSend,
       "type":blob.type,
       "size":blob.size
   }});
}

这是使用 https://github.com/muaz-khan/RTCMultiConnection 发送的,但主要问题是如何在发送后重建blob。可惜直接发送blob没有起作用。


1
Chrome支持ArrayBuffer,而RTCMultiConection也支持它。Chrome中的Blob支持正在进行中。因此,现在您可以使用“fileReader.readAsArrayBuffer”。供您参考,这将起作用:connection.send(recorder.blob) RTCMultiConnection将自动共享整个Blob(任何大小)。远程用户将在“onFileEnd”事件中接收完整的Blob。 - Muaz Khan
1个回答

4

来源:使用JavaScript从base64字符串创建Blob 该方法可以正确地将base64数据转换回原始二进制数据。 为了提高性能,数据以sliceSize大小的块进行处理。 注意:源代码是使用TypeScript编写的。

    public static Base64ToBlob(b64Data, contentType = "", sliceSize = 512): Blob
    {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize)
        {
            const slice = byteCharacters.slice(offset, offset + sliceSize);
            const byteNumbers = new Array(slice.length);

            for (let i = 0; i < slice.length; i++)
            {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, { type: contentType });
        return blob;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接