JS之File对象与base64字符串之间的相互转换

File对象有两种形态,

在请求时为:

控制台输出为:

从formData中获得fileList对应的File对象,并转换为base64字符串,再转换回File对象,代码示例如下:

const fileList = uploadFormData.get("fileList");
console.log(fileList);
const reader = new FileReader();
reader.readAsDataURL(fileList);
reader.onload = () => {
  imgBase64.value = reader.result;
  console.log(imgBase64.value);
  console.log(base64ToFile(imgBase64.value, fileList.name));
};
reader.onerror = function (err) {
  console.log(err);
};

base64ToFile函数:

const base64ToFile = (base64, fileName) => {
  let data = base64.split(",");
  let type = data[0].match(/:(.*?);/)[1];
  let suffix = type.split("/")[1];
  const bstr = window.atob(data[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  // 利用构造函数创建File文件对象
  const file = new File([u8arr], `${fileName}.${suffix}`, {
    type: type,
  });
  return file;
};

 

posted @ 2024-08-02 16:49  罗毅豪  阅读(270)  评论(0编辑  收藏  举报