How to preview image before upload using jQuery - FileReader()

/ / 42 Comments

jQuery show image before upload it on the server : Here this article explains how to preview an image before uploading it on the server. Let's suppose you have an application where the user uploads bulk photo and then the users want to upload only some selected photo, in this case, we as a developer don't want to upload all images photos on the server. As this effect on server load cost effect etc.

So using HTML 5 FileReader() we can able to preview an image before its get uploaded. By this user can view thumbnail photos on the client side and select or choose the photo which he/she wants to get upload.

Below I have added detailed code on how to preview image before upload using jQuery and live example.

Output:

Using HTML5 FileReader() Preview Image - Show thumbnail image before uploading on server in jQuery javascript

What is FileReader?

The FileReader object lets web applications asynchronously read the contents of files ( or raw data buffers ) stored on the user's computer, using File or Blob objects to specify the file or data to read, which means that your program will not stall while a file is being read. This is particularly useful when dealing with large files.

File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.

The following code shows how to create a new instance of FileReader.


//*
var myReader = new FileReader();
//*

FileReader includes 4 options for reading a file:

  1. FileReader.readAsBinaryString(Blob|File) : The result property will contain the file/blob's data as a binary string. Every byte is represented by an integer in the range [0..255].
  2. FileReader.readAsText(Blob|File, opt_encoding) :   The result property will contain the file/blob's data as a text string. By default, the string is decoded as 'UTF-8'. Use the optional encoding parameter can specify a different format.
  3. FileReader.readAsDataURL(Blob|File) :   The result property will contain the file/blob's data encoded as a data URL.
  4. FileReader.readAsArrayBuffer(Blob|File) :  The result property will contain the file/blob's data as an ArrayBuffer object.

Once one of these read methods is called on your FileReader object, the onloadstart, onprogress, onloadonabortonerror, and onloadend can be used to track its progress.

While for the browsers that support HTML5 i.e. Internet Explorer 10 and 11+, Mozilla FireFox, Google Chrome and Opera, and so the image preview is displayed using HTML5 FileReader API

# HTML MARKUP:

Here we have added an input file tag and a div tag. This div tag is used as holder where we show our thumbnail image .i.e preview image before uploading it to the server with jQuery example given below.

//*
<div id="wrapper">       
   <input id="fileUpload" type="file" /><br />
   <div id="image-holder"> </div>
 </div>
//*

# jQuery Code: To set preview / thumb  image  using FileReader():

Here first we bind a change event to our input file tag, then will check whether the browser supports HTML5 FileReader method, if not then will show alert message .i. Your browser is not supported.

//*
$("#fileUpload").on('change', function () {

        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                    "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    });
//*

View Demo

BONUS - Multiple Image Preview before uploading in Jquery:

We have done with preview image before upload, so let go one step further. Now we are going to show you how to select multiple images and preview it before upload .i.e before the image is actually uploaded to the server using jQuery in Asp.net.

Also Read: How to preview videos before uploading on the server

For uploading multiple images, we need to add multiple attributes to our file input tag.

# HTML Markup:

<div id="wrapper">
    <input id="fileUpload" type="file" multiple />
    <br />
    <div id="image-holder"></div>
</div>

# jQuery:

Now we store the file length in a variable and make a For loop over it, to access all the images. Finally, our code for multiple image preview before upload looks like as shown below.

 $("#fileUpload").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

View Demo

You can also check these articles:

  1. An easy way to upload bulk images in Asp.net c#.
  2. Upload and resize the image in Asp.net using dropzone js.
  3. Preview Image before upload it with jQuery in Asp.net.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

42 Comments

  1. Neetika 09/01/2015 06:07:55
    How to delete images shown in preview using jquery ?
  2. Satinder singh 09/01/2015 09:09:10
    Hi neetika, Using .html() in jQuery, you can clear all the content. For example, here have added a button, and on click event am making my container html as empty refer https://jsfiddle.net/r1fvy3c7/17/"
  3. Ahmad 09/19/2015 06:03:22
    Thankoooooooooooooooooooooooo
  4. Satinder singh 09/22/2015 16:34:47
    Thank you for visiting
  5. jony 09/25/2015 10:28:40
    Hola amigo, yo lo copio tal cual lo tienes ahí pero no me muestra ninguna imagen previa, es decir, el input file me carga la imagen pero no se me visualiza, y al mirar en la consola me dice que no ha habido ningún error. me podrías mandar el archivo de ejemplo por correo? Muchas gracias y un saludo.
  6. Meg T 12/08/2015 15:56:54
    Thanks for this! Very helpful!
  7. Satinder singh 12/09/2015 16:24:08
    Hey Meg, Thanks for the reading Happy Coding :)
  8. naveeed 12/13/2015 21:58:07
    Hi ! please guide me how can i adjust width and height img thumbnail
  9. simeon 12/23/2015 21:20:09
    excellent! thank you very much!
  10. Manoj 12/25/2015 17:34:05
    Nice Tutorial.. :)
  11. Manoj 12/25/2015 17:36:57
    Nice tutorial.... :)
  12. Okay 01/14/2016 12:24:06
    i have copied your code as it is written but it has failed to show a preview. wth [ i want to dsplay only one image so i copied that one that produces ur screen shot shown
  13. Satinder singh 01/14/2016 15:58:33
    Hi, The above-given code is working fine, you can check the live demo https://jsfiddle.net/r1fvy3c7/76/ . Maybe you missed something while copying the code
  14. JimmyArts 02/15/2016 09:11:09
    What if our user chose, let say, 5 images and then wanna remove 1 or 2 images among them? Any way to let user just remove the mis-chosen image, not the whole selection?
  15. hoodedboy 02/20/2016 16:44:41
    That was great. I made website but i need more guidance . You will be a great guide for me. Plz help me whenever you get time.
  16. Salman Ramzan Sahu 02/26/2016 17:38:35
    Yes above code is not working unless you put jQuery code in document.ready(function{//code});
  17. jonz 02/27/2016 11:43:34
    Hi i want to add caption for each image and i want to select one pic from selected multiple pic as cover pic so i added radio button and a text field for caption in preview in image holder but after posting it , it is not getting correctly. bcoz i am not getting the preview as the order i selected. pls help me for this
  18. Satinder singh 03/01/2016 15:34:18
    Hi Jonz, Can you share your code, how you get selected files? Are you adding any class or any counter variable ?? do create Js Fiddle"
  19. naveen 05/02/2016 06:48:07
    How can i remove individual image from script.. I want that code can u help me please..
  20. Mahmood Ahmad 05/09/2016 06:58:34
    excellent! thank you very much!
  21. Oleg 05/17/2016 20:37:58
    When I press Delete button, it removes only selected image previews, but the image files still stay in the list and will be uploaded to the server when I press the Upload button. How to remove that files from the list too? Thank you!
  22. MarkG 06/09/2016 16:34:49
    Hello. How can I resize the images on its preview instead of previewing it on its original dimensions?
  23. Satinder singh 06/14/2016 11:18:05
    By defining the CSS class you can easily able to resize the image preview
  24. Prashanth Mysore 06/22/2016 05:47:28
    Hey Bro, I stuked One day on this concept finally am getting output after reading your article excellent article and very simple thank you so much bro and definitely ill share your article with my frnds.
  25. Nagarjuna 06/24/2016 12:04:10
    how to see video preview before uploading in angularjs
  26. Satinder singh 06/24/2016 12:31:19
    If you are using HTML5 video tag, then from FileReader API you can create Blob URL. Then set this Blob URL to your HTML5 video tag and preview the video
  27. Gagan Chhatwal 09/11/2016 09:47:26
    Hi Satinder, Paji you are great was looking for this tutorial, helped me a lot. A big Thanks to you bro cheers :)
  28. Satinder singh 09/16/2016 06:54:27
    Thanks Keep visiting
  29. dragonbooster 10/04/2016 13:01:33
    Overall code is good but i would like you to tweak some changes in your code like to make your file upload accept only images try adding this ""
  30. rajwant 12/08/2016 08:36:07
    very helpful...
  31. paramasita 12/30/2016 08:53:42
    hi sir, this is nice tutorial, and then i try to preview image in modal, but it cannot display in modal. what wrong sir???
  32. Vinod 02/13/2017 11:26:58
    When I press Delete button, it removes only selected image previews, but the image files still stay in the list and will be uploaded to the server when I press the Upload button. How to remove that files from the list too?
  33. Satinder singh 02/16/2017 10:11:03
    Hi Vinod, To delete image file from server, you need to write server side code .i.e delete file by filename or by id which might be saved somewhere in database
  34. Luan 03/14/2017 03:01:08
    Example : https://github.com/Luanramos/uploadPreview
  35. Gaurav jain 10/24/2017 13:13:30
    I am looking something different. I don't want to upload/store image in folder and image path in database table because if some one delete image from folder. So I want to store image in database table and fetch image from table and show same image on webpage. Can you help me
  36. Satinder singh 10/26/2017 07:07:25
    Good work Luan,
  37. Satinder singh 10/26/2017 07:09:40
    Hi paramsita, Here the link https://base64-image.codepedia.info/base64-image/index.html which display image in Modal Popup
  38. ahmed 02/08/2018 08:42:52
    Thanks for this!
  39. ahsan abrar 02/24/2018 18:37:43
    thank you so much Sir.
  40. Gwein 11/01/2018 08:09:52
    Hi sir, how to make a hero thumbnail ? I mean in this example I upload 4 image and I want one of those image become hero ( big thumbnail and the rest is small ) And if I click to other image, they swap And also, how to make an image become the first thumbnail in database ? If you can explain this, damn, you are the man
  41. Sagar 02/04/2021 11:47:33
    Nice Work! But how can we display videos and images preview both using this code? Can you explain it with bit more code