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>
相关推荐
hongkid8 分钟前
React Native 如何打包正式apk
javascript·react native·react.js
李少兄10 分钟前
简单讲讲 SVG:前端开发中的矢量图形
前端·svg
前端小万11 分钟前
告别 CJS 库加载兼容坑
前端·前端工程化
恋猫de小郭11 分钟前
Flutter 3.38.1 之后,因为某些框架低级错误导致提交 Store 被拒
android·前端·flutter
JarvanMo15 分钟前
Flutter 需要 Hooks 吗?
前端
光影少年26 分钟前
前端如何虚拟列表优化?
前端·react native·react.js
Moment27 分钟前
一杯茶时间带你基于 Yjs 和 reactflow 构建协同流程图编辑器 😍😍😍
前端·后端·面试
菩提祖师_41 分钟前
量子机器学习在时间序列预测中的应用
开发语言·javascript·爬虫·flutter
invicinble1 小时前
对于前端数据的生命周期的认识
前端
PieroPc1 小时前
用FastAPI 后端 和 HTML/CSS/JavaScript 前端写一个博客系统 例
前端·html·fastapi