Preview an image before it is uploaded

ghz 1years ago ⋅ 927 views

Question

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.

How can I do this?


Answer

imgInp.onchange = evt => {
  const [file] = imgInp.files
  if (file) {
    blah.src = URL.createObjectURL(file)
  }
}


<form runat="server">
  <input accept="image/*" type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" />
</form>