在过程中,发现报错如下:
failed to execute ‘atob’ on ‘window’: the string to be decoded is not correctly encoded.
在Google后,仍然不能解决,~~o(>_<)o ~~
后来在看atob和btoa的demo时发现base64字符串仅仅是后面的乱七八糟字符串好吗,没有前面的名片。
var str = “Hello World!”;
var enc = window.btoa(str);
var dec = window.atob(enc);
var res = “Encoded String: ” + enc + “
” + “Decoded String: ” + dec;
The result of res will be:
Encoded String: SGVsbG8gV29ybGQh //看这里!!!!
Decoded String: Hello World!
而图片的base64是这样的:
data:image/gif;base64,/9j/4AAQSkZJRgABAQ……..
所以只要后面的就可以了:
b64Data.substring(b64Data.indexOf(‘,’) + 1)
base64转换blob函数
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data.substring(b64Data.indexOf(',') + 1));
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;
};