js的File对象,Blob和file相互转换

示例

javascript 复制代码
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>js的File对象,Blob和file相互转换</title>
  <style>
    .prview {
      display: flex;
      margin: 10px;
    }

    .prview .rename {
      display: inline-block;
      width: 60px;
    }

    .prview img {
      width: 200px;
      height: 200px;
    }
  </style>
</head>

<body>
  <input type="file" onchange="upload(this)" />

  <div class="prview">
    <span class="rename">base64:</span>
    <img id="base64" src="" alt="" />
  </div>
  <div class="prview">
    <span class="rename">blob:</span>
    <img id="blob" src="" alt="" />
  </div>

  <script>
    const upload = async (e) => {
      let files = e.files[0];
      console.log(files);

      // file转base64
      let base64 = await fileToBase64(files);
      setImage('base64', base64) //设置图片

      // base64转blob
      let blob = parseBlob(base64);
      setImage('blob', blob) //设置图片

      // blob转file
      let file = blobToFile(blob);
      console.log(file);
    };

    // blob转file
    const blobToFile = (blob) => {
      let rename = new Date().getTime() + ".png";
      let file = new File([blob], rename, { type: "image/png" });
      return file;
    };

    // base64转blob
    const parseBlob = (base64) => {
      var arr = base64.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      for (var i = 0; i < n; i++) {
        u8arr[i] = bstr.charCodeAt(i);
      }
      var url = URL || webkitURL;
      return url.createObjectURL(new Blob([u8arr], { type: mime }));
    };

    // file转base64
    const fileToBase64 = (file) => {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    };

    // 设置格式到图片
    const setImage = (id, val) => {
      let img = document.getElementById(id)
      img.setAttribute('src', val)
    }
  </script>
</body>

</html>
相关推荐
CHU7290356 分钟前
生鲜商城小程序前端功能版块:适配生鲜采购核心需求
前端·小程序
huangyiyi6666620 分钟前
Vue + TS 项目文件结构
前端·javascript·vue.js
0思必得038 分钟前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化
徐同保1 小时前
react-markdown使用
前端·react.js·前端框架
2601_949857431 小时前
Flutter for OpenHarmony Web开发助手App实战:CSS参考
前端·css·flutter
无法长大1 小时前
如何判断项目需不需要用、能不能用Tailwind CSS
前端·css·vue.js·elementui·vue3·tailwind css
橙露1 小时前
移动端前端适配:Rem、VW/VH 与媒体查询的综合应用指南
前端·媒体
GGGG寄了1 小时前
CSS——CSS引入方式+选择器类型
前端·css·html
墨染青竹梦悠然1 小时前
基于Django+vue的图书借阅管理系统
前端·vue.js·后端·python·django·毕业设计·毕设
码农六六1 小时前
js函数柯里化
开发语言·前端·javascript