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
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
- Error: error:0308010C:digital envelope routines::unsupported
Related Article