Front-end base64 to file file method
background
There is such a scenario, for example, the canvas intercepts part of the dom as a picture and uploads it to the server, and the picture intercepted by the canvas returns a base64 string, while the server receives a file file. Therefore, we need to convert the base64 string into a file and store it in the server.
Solution
- Method 1: Use new File() to directly convert base64 into a file file. (This method needs to consider browser compatibility issues)
// 第一个参数dataUrl是一个base64的字符串。第二个参数是文件名可以随意命名
function base64toFile(dataurl, filename = 'file') {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
// suffix是该文件的后缀
let suffix = mime.split('/')[1];
// atob 对经过 base-64 编码的字符串进行解码
let bstr = atob(arr[1]);
// n 是解码后的长度
let n = bstr.length;
// Uint8Array 数组类型表示一个 8 位无符号整型数组 初始值都是 数子0
let u8arr = new Uint8Array(n);
// charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// new File返回File对象 第一个参数是 ArraryBuffer 或 Bolb 或Arrary 第二个参数是文件名
// 第三个参数是 要放到文件中的内容的 MIME 类型
return new File([u8arr], `${
filename}.${
suffix}`, {
type: mime,
});
}
- Method 2: Convert base64 to blob first, and then convert blob to file. This method does not have browser incompatibility issues.
//1,先将base64转换为blob
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime });
}
//2,再将blob转换为file
function blobToFile(theBlob, fileName){
theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
theBlob.name = fileName; // 文件名
return new File([theBlob], fileName, {
type: theBlob.type, lastModified: Date.now()});
}
// 使用示例
function base64toFile(file) {
// 1.先转为 blob格式 file.content是此文件的base64格式
let blob = this.dataURLtoBlob(file.content);
// 拿到文件名
let fileName = file.file.name;
// 2,在转为 file类型
let file1 = this.blobToFile(blob,fileName);
console.log("file1:",file1);
// 3,上传...
}
article reference
https://blog.csdn.net/qq_43886365/article/details/126729188