在JavaScript中从base64字符串创建Blob我在字符串中有base64编码的二进制数据。const contentType = 'image/png';const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8
/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';我想创建一个blob:包含此数据的URL并将其显示给用户。const blob = new Blob(????, {type: contentType});const blobUrl = URL.createObjectURL(blob);window.location = blobUrl;我还没有弄清楚如何创建Blob。在某些情况下,我可以通过使用data:URL 来避免这种情况。const dataUrl = `data:${contentType};base64,${b64Data}`;window.location = dataUrl;但是在大多数情况下,data:URL非常大。如何Blob在JavaScript中将base64字符串解码为对象?
4 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
优化(但不太可读)的实现:
function base64toBlob(base64Data, contentType) { contentType = contentType || ''; var sliceSize = 1024; var byteCharacters = atob(base64Data); var bytesLength = byteCharacters.length; var slicesCount = Math.ceil(bytesLength / sliceSize); var byteArrays = new Array(slicesCount); for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { var begin = sliceIndex * sliceSize; var end = Math.min(begin + sliceSize, bytesLength); var bytes = new Array(end - begin); for (var offset = begin, i = 0; offset < end; ++i, ++offset) { bytes[i] = byteCharacters[offset].charCodeAt(0); } byteArrays[sliceIndex] = new Uint8Array(bytes); } return new Blob(byteArrays, { type: contentType });}
添加回答
举报
0/150
提交
取消