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>
相关推荐
主宰者17 分钟前
C# CommunityToolkit.Mvvm全局事件
java·前端·c#
老神在在00121 分钟前
【Selenium 自动化精讲】浏览器弹窗与登录界面的本质区别 & 实操指南
javascript·学习·selenium·测试工具·自动化
前端小咸鱼一条1 小时前
16.迭代器 和 生成器
开发语言·前端·javascript
小江的记录本1 小时前
【注解】常见 Java 注解系统性知识体系总结(附《全方位对比表》+ 思维导图)
java·前端·spring boot·后端·spring·mybatis·web
web守墓人1 小时前
【前端】记一次将ruoyi vue3 element-plus迁移到arco design vue的经历
前端·vue.js·arco design
伊步沁心1 小时前
Webpack & Vite 深度解析
前端
libokaifa1 小时前
OpenSpec + TDD:让 AI 写代码,用测试兜底
前端·ai编程
用户15815963743701 小时前
搭 AI Agent 团队踩了 18 个坑,总结出这 5 个关键步骤
前端
Kellen1 小时前
Fumadocs 基础概念:从内容源到页面渲染
前端
Lee川1 小时前
前端进阶之路:从性能优化到响应式布局的实战指南(Tailwindcss)
前端·面试