base64转file;兼容IE
1 //将base64转换为文件,dataurl为base64字符串,filename为文件名(必须带后缀名,如.jpg,.png)|||| 2 var arr = newBase64.split(','), 3 mime = arr[0].match(/:(.*?);/)[1], 4 bstr = atob(arr[1]), 5 n = bstr.length, 6 u8arr = new Uint8Array(n); 7 while(n--){ 8 u8arr[n] = bstr.charCodeAt(n); 9 } 10 var imgObj = new File([u8arr], "baseImg.jpg", {type:mime});
但是不兼容ie,解决如下;先将base64转成blob流,后将二进制流转化为file文件
1 var blob = dataURLtoBlob(base64Data); 2 var file = blobToFile(blob, "zjName.png"); 3 4 function dataURLtoBlob(dataurl) {//base64转二进制流 5 var arr = dataurl.split(','), 6 mime = arr[0].match(/:(.*?);/)[1], 7 bstr = atob(arr[1]), 8 n = bstr.length, 9 u8arr = new Uint8Array(n); 10 while (n--) { 11 u8arr[n] = bstr.charCodeAt(n); 12 } 13 return new Blob([u8arr], { type: mime }) 14 }
15 function blobToFile(theBlob,fileName) { //二进制流转文件 16 theBlob.lastModifiedDate = new Date(); 17 theBlob.name = fileName; 18 return theBlob; 19 }