preview image before it is uploaded

How to Preview Image Before It is Uploaded Using jQuery

jQuery is a powerful JavaScript library that allows you to perform many useful DOM manipulations as well as work with files and images. Sometimes you may need to preview an image before it is uploaded to your web server. This is often required if you are running an ecommerce website or social media app. This can be easily done using jQuery. In this article, we will learn how to preview image before it is uploaded using jQuery.


How to Preview Image Before It is Uploaded Using jQuery

Let us say you have the following HTML code.

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

To preview an uploaded image, just add the following jQuery code to your web page.

<script>

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

</script>

We have basically attached onchange event handler to file input. We store the path uploaded file in file variable. Then we call URL.createObjectURL() function to create a DOM string for the image. This is passed to image tag’s src attribute to load the image preview.

You can also use FileReader API to create a Base64 representation of image in memory and load the image in browser.

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

In the above code, we have learnt a couple of ways to preview image before it is uploaded in jQuery.

Also read:

How to Get Image Size & Width Using JavaScript
How to Use Multiple jQuery Versions On Same Page
How to Convert Form Data to JS Object Using jQuery
How to Detect Mobile Device Using jQuery
How to Bind Event to Dynamic Element in jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *