前言: 作为前端项目开发,经常会遇到图片文件的处理,下面总结一下关于 Base64、File对象和Blob 的相互转换大全。让我们一起学习吧!
1. file 对象转 base64
/**
* file 对象转 base64
* @param file
* @param callback
*/exportconstfileToBase64=(file, callback)=>{const fileReader =newFileReader();
fileReader.readAsDataURL(file);
fileReader.onload=function(){callback(this.result);};};
2. base64 直接转换为 file
/**
* base64 转换为 file
* 先将base64转换成blob,再将blob转换成file文件,此方法不存在浏览器不兼容问题
* @param base64Url
* @param filename
* @returns
*/exportconstbase64UrlToFile=(base64Url, filename)=>{// 获取到base64编码const arr = base64Url.split(',');const mime = arr[0].match(/:(.*?);/)[1];// 将base64编码转为字符串const bstr =atob(arr[1]);let n = bstr.length;// 创建初始化为0的,包含length个元素的无符号整型数组const u8arr =newUint8Array(n);while(n--){
u8arr[n]= bstr.charCodeAt(n);}returnnewFile([u8arr], filename,{ type: mime });};
3. base64 转换成 blob
/**
* base64 转换成 blob
* @param dataUrl
* @returns
*/exportconstdataURLtoBlob= dataUrl =>{const arr = dataUrl.split(',');const mime = arr[0].match(/:(.*?);/)[1];const bstr =atob(arr[1]);let n = bstr.length;const u8arr =newUint8Array(n);while(n--){
u8arr[n]= bstr.charCodeAt(n);}returnnewBlob([u8arr],{ type: mime });};
4. blob 转换为 file
/**
* blob 转换为 file
* @param blobObj
* @param fileName
* @returns
*/exportconstblobToFile=(blobObj, fileName)=>{
blobObj.lastModifiedDate =newDate();// 文件最后的修改日期
blobObj.name = fileName;// 文件名returnnewFile([blobObj], fileName,{ type: blobObj.type, lastModified: Date.now()});};
5. base64 转 file 对象【仅思路步骤,实质同上的直转一样】
/**
* base64 转换成 blob
* @param dataUrl
* @returns
*/exportconstdataURLtoBlob= dataUrl =>{const arr = dataUrl.split(',');const mime = arr[0].match(/:(.*?);/)[1];const bstr =atob(arr[1]);let n = bstr.length;const u8arr =newUint8Array(n);while(n--){
u8arr[n]= bstr.charCodeAt(n);}returnnewBlob([u8arr],{ type: mime });};/**
* blob 转换为 file
* @param blobObj
* @param fileName
* @returns
*/exportconstblobToFile=(blobObj, fileName)=>{
blobObj.lastModifiedDate =newDate();// 文件最后的修改日期
blobObj.name = fileName;// 文件名returnnewFile([blobObj], fileName,{ type: blobObj.type, lastModified: Date.now()});};/**
* base64 转 file 对象
* // 先将base64转换成blob,再将blob转换成file文件,此方法不存在浏览器不兼容问题
* @param dataUrl
* @param fileName
* @returns
*/exportconstbase64ToFile=(dataUrl, fileName)=>{const theBlob =dataURLtoBlob(dataUrl);returnblobToFile(theBlob, fileName);};
本文转载自: https://blog.csdn.net/yiguoxiaohai/article/details/129195167
版权归原作者 迷途小码农零零发 所有, 如有侵权,请联系我们删除。
版权归原作者 迷途小码农零零发 所有, 如有侵权,请联系我们删除。