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 address detailed code on how to preview image before upload using jQuery and live example.
Screenshot:
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:
- 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].
- 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.
- FileReader.readAsDataURL(Blob|File) : The result property will contain the file/blob’s data encoded as a data URL.
- 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, onload, onabort, onerror, 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.");
}
});
//*
Try it Yourself »
Output: Using html 5 FileReader() we preview an image before upload.
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.
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");
}
});
Try it Yourself »
You can also check these articles:
- An easy way to upload bulk images in Asp.net c#.
- Upload and resize the image in Asp.net using dropzone js.
- Preview Image before upload it with jQuery in Asp.net.
Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!
43 comments on “How to preview image before upload using jQuery – FileReader()”
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
thank you so much Sir.
Thanks for this!
Example : https://github.com/Luanramos/uploadPreview
Good work Luan,
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?
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
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
Hi Gaurav,
This post is about preview image on client-side.
AS you want to display the image from the database, there are 2 possibilities if your images are saved in binary format then here similar article Display image from Binary Data.
else if you just saving path, then by setting path will work for you
hi sir, this is nice tutorial, and then i try to preview image in modal, but it cannot display in modal. what wrong sir???
Hi paramsita,
Here the link https://base64-image.codepedia.info/base64-image/index.html which display image in Modal Popup
very helpful…
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 “”
Hi Satinder, Paji you are great was looking for this tutorial, helped me a lot. A big Thanks to you bro cheers 🙂
Thanks Keep visiting
how to see video preview before uploading in angularjs
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
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.
Hello. How can I resize the images on its preview instead of previewing it on its original dimensions?
By defining the CSS class you can easily able to resize the image preview
excellent! thank you very much!
How can i remove individual image from script..
I want that code can u help me please..
Hello Naveen,
For removing individual images you can use jquery .remove() method, this will eliminate all the selected the pictures. For selecting images you have to add a class to it.
Live Demo https://codepedia.info/editor-example/delete-images-jquery/
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!
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
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
Yes above code is not working unless you put jQuery code in document.ready(function{//code});
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.
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?
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
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
Nice tutorial…. 🙂
Nice Tutorial.. 🙂
excellent! thank you very much!
Hi ! please guide me how can i adjust width and height img thumbnail
Hi Naveed, If you go through the above code you will see, while adding an image tag to preview image have also added a CSS class “thumb-image”. You can set any height, width to “thumb-image” as per your need.
Thanks for this! Very helpful!
Hey Meg,
Thanks for the reading
Happy Coding 🙂
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.
Thankoooooooooooooooooooooooo
Thank you for visiting
How to delete images shown in preview using jquery ?
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 referhttps://jsfiddle.net/r1fvy3c7/17/