Computer >> Computer tutorials >  >> Programming >> Javascript

Preview an image before it is uploaded in JavaScript


For security reasons browsers do not allow accessing the path of the image file selected via an input, i.e.JavaScript in browsers has no access to the File System. Therefore, our task is to preview the image file selected via the input before we send it to any server or anywhere else.

Method 1: Using the URL class:

WE can use the createObjectURL() function of the URL class to create a url of the image selected by the input and then provide that url to the src attribute of an img tag.

Example

The code for this will be −

<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
   const previewImage = e => {
      const preview = document.getElementById('preview');
      preview.src = URL.createObjectURL(e.target.files[0]);
      preview.onload = () => URL.revokeObjectURL(preview.src);
   };
</script>

Method 2: Using the FileReader class:

This method will parse the file taken in by the <input /> and then it will create a string containing a base64 representation of the image.

Example

The code for this will be −

<img id="preview"/>
<input type="file" accept="image/*" onchange="previewImage(event)">
<script>
   const previewImage = e => {
      const reader = new FileReader();
      reader.readAsDataURL(e.target.files[0]);
      reader.onload = () => {
         const preview = document.getElementById('preview');
         preview.src = reader.result;
      };
   };
</script>

Output

The output for both the methods will look like −

Preview an image before it is uploaded in JavaScript