• html 预览图片


    首先你需要让用户上传图片

    <input type="file" accept="image/*" id="upfile"  />
    

    默认会让用户在 相册 或则 摄像头 中选择,如果加上 capture="camera" 则默认打开摄像头

    当上传图片时,先在本地预览图片

    document.querySelector("#upfile").addEventListener("change", handleFiles);
    
    async function handleFiles(e) {
      const files = e.target.files;
      // 1
      const reader = new FileReader();
      reader.readAsDataURL(files[0]);
      reader.onload = (e) => {
        const base64data = e.target.result;
        createImg(base64data);
      };
    
      // 2
      createImg(files[0]);
    }
    
    function createImg(src) {
      const img = document.createElement("img");
      img.width = 200;
      img.height = 200;
    
      if ((src + "").includes("base64")) {
        img.src = src;
      } else {
        const imgSrc = window.URL.createObjectURL(src); // window.URL.revokeObjectURL(imgSrc)
        img.src = imgSrc;
      }
      document.body.appendChild(img);
    }
    
  • 相关阅读:
    将博客搬至CSDN
    defender 月考总结
    生日祝福@陈俊翰
    个性签名
    你这是virus吧?
    (CPSCA's)CPOJC+VIJOS
    Sentence by defender
    工作制一览
    最长上升子序列
    mysql约束
  • 原文地址:https://www.cnblogs.com/ajanuw/p/8075537.html
Copyright © 2020-2023  润新知