我可以使用 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 无效。
最佳答案
来源:Creating a Blob from a base64 string in JavaScript 此方法正确地将 base64 数据转换回原始二进制数据。 为了提高性能,数据以 sliceSize 大小的 block 为单位进行处理。 注意:源代码在 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;
}
关于Javascript 将 blob 转换为字符串并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36301315/