base64图片格式|base64图片格式 跟input type= ‘file’ 选择的表单文件格式相互转换

前端在做开发的过程中少不了要上传文件或者图片到服务器端,有时候上传图片是用base64格式上传,有时候接口则是要求用表单的文件流形式上传。下面两个方法就是对图片形式进行转换。
1.base64转 file 表单形式
function dataURLtoFile(dataurl,filename){
//将base64转换为文件
vararr=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);
}
returnnewFile([u8arr],filename,{type:mime});
}
varfile=dataURLtoFile(imgUrl,"img");


2.file 图片转base64base64转blob,blob转file
function dataURLtoBlob(dataurl)
{
vararr=dataurl.split(','),
mime=arr[0].match(/:(.*?); /)[1],
bstr=atob(arr[1]),
n=bstr.length,
u8arr=newUint8Array(n);
while(n--){
u8arr[n]=bstr.charCodeAt(n);
}
returnnewBlob([u8arr],{type:mime});
};
//将blob转换为file
functionblobToFile:(theBlob,fileName){
theBlob.lastModifiedDate= new Date();
theBlob.name=fileName;
returntheBlob;
};
//调用
varblob=dataURLtoBlob(base64Data);
【base64图片格式|base64图片格式 跟input type= ‘file’ 选择的表单文件格式相互转换】varfile=blobToFile(blob,imgName);

    推荐阅读