未捕获的InvalidCharacterError:无法从base64图像转换为blob

时间:2016-07-26 00:17:17

标签: javascript node.js base64 blob

我尝试将base64转换为blob,但错误未捕获InvalidCharacterError:无法在'Window'上执行'atob':要解码的字符串未正确编码。

我在这里测试了我的base64图像数据http://codebeautify.org/base64-to-image-converter并且它工作正常,我能够看到图像渲染得很好

 function b64toBlob(b64Data, contentType, sliceSize) {
            contentType = contentType || '';
            sliceSize = sliceSize || 512;

            var byteCharacters = atob(b64Data);
            var byteArrays = [];

            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var slice = byteCharacters.slice(offset, offset + sliceSize);

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

                var byteArray = new Uint8Array(byteNumbers);

                byteArrays.push(byteArray);
            }

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

      var blob = b64toBlob(base64Data, 'image/jpeg'); 
      console.log(blob)

https://jsfiddle.net/wfh5fjn9/

1 个答案:

答案 0 :(得分:1)

发生的事情是您将data:image/jpeg;base64,保留在base64Data字符串中。您需要删除它,并且只保留实际上 base64编码的字符串才能工作。

换句话说,

var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ' // truncated

变为

var base64Data = '/9j/4AAQSkZJRgABAQ' // truncated

https://jsfiddle.net/wfh5fjn9/1/