Sometimes we face requirement to show image preview to user before uploading to server so they can verify which image or images are selected by them and if wrong images are selected then they can remove it before uploading to server. Social media site and hosting platform provides this type of functionality where user can review and change images before uploading.
We can create similar functionality for showing image preview easily using jQuery. In this article, we will take simple example where user can select image file and jQuery will show preview of selected file.
First of all, let's define basic markup for our web page then we will add our code for showing image preview. Here, you can use existing code or copy below code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ImagePreview Using JavaScript</title>
</head>
<body>
<input id="image" type="file" name="image">
<div id="imageDisplay"> </div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
Here, we just added simple input field with file type and assign ID to it. Also defined HTML div element which is used to show image preview to user.
Here, we are going to use FileReader object to show image preview. The FileReader allow web applications asynchronously read the contents of user's files, 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. It will commonly used to deal with large files.
Following is code sample to create a new instance of FileReader.
var fr = new FileReader();
In this example, we will bind input with change event and apply our logic into that function. The change event will be trigger when user select image file. Let's take example to create our functionality. Add below code at end of body tag.
$("#image").on('change', function () {
var fr = new FileReader();
if (typeof (FileReader) != "undefined") {
var imageDisplay = $("#imageDisplay");
imageDisplay.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("
", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(imageDisplay);
}
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("Your browser does not support FileReader.");
}
});
In the above code, first of all, we have defined on change event and when on change event triggers it will create new instance of FileReader. Then empty image display div. At last, it will create new image element and append it to image display image.
In this article, we have taken simple example show image preview to user using jQuery and FileReader based logic. There are many ready to use library to perform this task easily.
Ask anything about this examples