In this article, I will show you how to preview an image before uploading to the server using jQuery.You can preview the selected photos with the help of HTML5 FileReader(). The FileReader() objects asynchronously read the content files and store on the user’s computer.
In Previous article I explained, Html5 file upload multiple to server using asp.net mvc.
HTML5 upload file example code:
<html>
<head>
<style type="text/css">
.thumb-image {
float: left;
width: 100px;
position: relative;
padding: 5px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div id="wrapper" style="margin-top: 20px; width: 500px; height: 350px; border: 1px solid #d9d3d3;">
<h2>HTML5 upload image preview</h2>
<br />
<input id="fileUpload" multiple="multiple" type="file" />
<div id="image-holder"></div>
</div>
<script>
$(document).ready(function () {
$("#fileUpload").on('change', function () {
//Getcount 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("Please select only images");
}
});
});
</script>
</body></html>
Description: I have added the div element and input file tag. The user can preview an image in the div tag before uploading it to the server.
Ouput: HTML5 preview image
Post your comments / questions
Recent Article
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
Related Article