vue3 把base64转成file文件的问题

网上有许多,我就随便复制了两个,但发现了一些问题

1.通过new File()将base64转换成file文件,此方式需考虑浏览器兼容问题。
// 将base64转换为文件
const dataURLtoFile=(dataurl, filename)=> {
  let arr = dataurl.split(",");
  let  mime = arr[0].match(/:(.*?);/)[1];
  let  bstr = window.atob(arr[1]);
  let  n = bstr.length;
  let  u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

//调用
let file = dataURLtoFile(base64Data, imgName);

2.先将base64转换成blob,再将blob转换成file文件,此方法不存在浏览器不兼容问题。
// 将base64转换为blob
const dataURLtoBlob=(dataurl)=> {
  let arr = dataurl.split(",");
  let  mime = arr[0].match(/:(.*?);/)[1];
  let  bstr = window.atob(arr[1]);
  let  n = bstr.length;
  let  u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
// 将blob转换为file
const blobToFile=(theBlob, fileName)=> {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}
// 调用
let blob = dataURLtoBlob(base64Data);
let file = blobToFile(blob, imgName);
}

一,atob报错,报编码问题(Failed to execute 'atob' on 'Window': Th...),后来去网上查了一下

  1,base64包含特殊字符要去掉

    base64.replace(/%0A|\s/g,''))//去掉%和A,我没有试过,还有其它方法自行查找

  2,借助 encodeURIComponent 和 decodeURIComponent 转义非中文字符

    使用decodeURIComponent 转义decodeURIComponent(dataurl)把base64转成ASCII字符序列就可以了

二,文件名的问题

  这里的文件名应该在后面加上一个格式不然后端可能会报错返回

  

 

 如果不知道怎么上传file文件,可以查看这个:https://www.cnblogs.com/whenwei123/p/16384590.html

 

posted @ 2022-06-27 14:50  light丶  阅读(3200)  评论(0)    收藏  举报