Skip to content

Instantly share code, notes, and snippets.

@renzhezhilu
Created October 10, 2019 02:45
Show Gist options
  • Save renzhezhilu/e4ba0bb11e202d92949e9fd67a65869d to your computer and use it in GitHub Desktop.
Save renzhezhilu/e4ba0bb11e202d92949e9fd67a65869d to your computer and use it in GitHub Desktop.
[blob和base64互相转换]#浏览器全局对象 #数据转换
//blob转base64
function blobToDataURI(blob, callback) {
let reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result);
}
reader.readAsDataURL(blob);
}
//base64转blob
function dataURItoBlob(dataURI) {
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
let byteString = atob(dataURI.split(',')[1]); //base64 解码
let arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
let intArray = new Uint8Array(arrayBuffer); //创建视图
for (let i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([intArray], {
type: mimeString
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment