【问题标题】:Javascript convert blob to string and backJavascript将blob转换为字符串并返回
【发布时间】:2016-03-30 06:30:32
【问题描述】:

我可以使用 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 无效。

【问题讨论】:

  • Chrome 支持数组缓冲区,RTCMultiConection 也支持。 chrome 中的 Blob 支持正在进行中。所以现在,你可以使用“fileReader.readAsArrayBuffer”。供您参考,这将起作用:connection.send(recorder.blob) RTCMultiConnection 将自动共享整个 blob(任何大小)。远程用户将在“onFileEnd”事件中收到完整的 blob。

标签: javascript filereader


【解决方案1】:

来源:Creating a Blob from a base64 string in JavaScript 此方法正确地将 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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    相关资源
    最近更新 更多