1. 先转blob,再转File(兼容好)
//将base64转换为blob dataURLtoBlob: function(dataurl) { var arr = dataurl.split(',') var mime = arr[0].match(/:(.*?);/)[1] var bstr = atob(arr[1]) var n = bstr.length var u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, //将blob转换为file blobToFile: function(theBlob, fileName){ theBlob.lastModifiedDate = new Date(); theBlob.name = fileName; return theBlob; }, //调用 var blob = dataURLtoBlob(base64Data); var file = blobToFile(blob, imgName);
2. 直接转File(兼容差)
//将base64转换为文件 dataURLtoFile: function(dataurl, filename) { var arr = dataurl.split(',') var mime = arr[0].match(/:(.*?);/)[1] var bstr = atob(arr[1]) var n = bstr.length var u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } //调用 var file = dataURLtoFile(base64Data, imgName);
出处:https://lolosong.com/post/base64tofile.html