How to Preview an image before uploading image in JavaScript

In this article, I am going to show you how to preview an image before uploading in the server using JavaScript.

HTML has many types of input functions, one of which is text, passwords, emails, etc. that we always use. There is also another type of input known as the file input (<input type=" file">). Here you can use any type of file for input.

Step 1: Create the basic structure of the image preview

<label for="file-ip-1">Upload Image</label>
<input type="file" accept="image/*" onchange="showPreview(event);">

<img id="image-preview" />

Step 2: Preview the Image with JavaScript code

Now, We will create a function called showPreview. This function will get the file and create a URL with the help of URL.createObjectURL function. The showPreview function will call once user select the image.

<script type="text/javascript">
function showPreview(event){
  if(event.target.files.length > 0){
    var src = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById("image-preview");
    preview.src = src;
  }
}
</script>

Congratulation!!, You have successfully created Image Viewer

A complete Example

If you are still confused and want to see it on working condition. You need to follow below setups

  • You need to create a file named index.html
  • Copy the below code and paste it on index.html file then save the file and open that file in browser.
<label for="file-ip-1">Upload Image</label>
<input type="file" accept="image/*" onchange="showPreview(event);">

<img id="image-preview" />

<script type="text/javascript">
function showPreview(event){
  if(event.target.files.length > 0){
    var src = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById("image-preview");
    preview.src = src;
  }
}
</script>

Recommended Posts

Comments are closed.