前言: 作为前端项目开发,经常会遇到图片文件的处理,下面总结一下关于 Base64、File对象和Blob 的相互转换大全。让我们一起学习吧!
1. file 对象转 base64
export const fileToBase64 = (file, callback) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function () {
callback(this.result);
};
};
2. base64 直接转换为 file
export const base64UrlToFile = (base64Url, filename) => {
const arr = base64Url.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
};
3. base64 转换成 blob
export const dataURLtoBlob = dataUrl => {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
4. blob 转换为 file
export const blobToFile = (blobObj, fileName) => {
blobObj.lastModifiedDate = new Date();
blobObj.name = fileName;
return new File([blobObj], fileName, { type: blobObj.type, lastModified: Date.now() });
};
5. base64 转 file 对象【仅思路步骤,实质同上的直转一样】
export const dataURLtoBlob = dataUrl => {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
export const blobToFile = (blobObj, fileName) => {
blobObj.lastModifiedDate = new Date();
blobObj.name = fileName;
return new File([blobObj], fileName, { type: blobObj.type, lastModified: Date.now() });
};
export const base64ToFile = (dataUrl, fileName) => {
const theBlob = dataURLtoBlob(dataUrl);
return blobToFile(theBlob, fileName);
};