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);
}
原文地址:https://www.cnblogs.com/ajanuw/p/8075537.html