When a File is selected, a check is performed to determine whether the file is a valid image file using
Regular Expressions and then using
HTML5 FileReader API, the File selected in the
FileUpload control is read as
BASE64 string using the
readAsDataURL method and is displayed using an
Image element.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
$("#fileupload").change(function () {
$("#dvPreview").html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
if (regex.test($(this).val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
$("#dvPreview").append("<img />");
$("#dvPreview img").attr("src", e.target.result);
}
reader.readAsDataURL($(this)[0].files[0]);
}
}else {
alert("Please upload a valid image file.");
}
});
});
</script>
* All browser logos displayed above are property of their respective owners.