Hi friends,in this article I will explain about how to preview image before upload using FileUpload control and
jQuery in ASP.NET
While for the browsers that support HTML5 i.e. Internet Explorer 10 and 11+, Mozilla FireFox, Google Chrome and Opera, the image preview is displayed usingHTML5 FileReader API.
Preview image before upload using FileUpload control and
jQuery in ASP.NET
Method 1:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>Preview
image before upload using FileUpload control and jQuery in ASP.NET </title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function PreviewImageBeforeUpload(Imagepath) {
if (Imagepath.files && Imagepath.files[0])
{
var
Filerdr = new FileReader();
Filerdr.onload
= function (e) {
$('#ImagePreview').attr('src',
e.target.result);
}
Filerdr.readAsDataURL(Imagepath.files[0]);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FilePreview"
runat="server"
onchange="PreviewImageBeforeUpload(this);"
/>
<br />
<asp:Image ID="ImagePreview"
runat="server"
Width="150px"
Height="150px"
/>
<asp:Button ID="btnSubmit"
runat="server"
Text="Upload"
/>
</div>
</form>
</body>
</html>
|
The Method 2 is shown using the DXImageTransform filter CSS property in browsers that do not support HTML5 i.e. Internet Explorer 8 and 9.
Method 2:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title>Preview
image before upload using FileUpload control and jQuery in ASP.NET
</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function () {
$("#FilePreview").change(function () {
$("#ImagePreview").html("");
var regex =
/^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
if (regex.test($(this).val().toLowerCase()))
{
if ($.browser.msie &&
parseFloat(jQuery.browser.version) <= 9.0) {
$("#ImagePreview").show();
$("#ImagePreview")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src
= $(this).val();
}
else {
$("#ImagePreview").show();
$("#ImagePreview").append("<img />");
var Filerdr = new
FileReader();
Filerdr.onload
= function (e) {
$("#ImagePreview img").attr("src", e.target.result);
}
Filerdr.readAsDataURL($(this)[0].files[0]);
}
} else {
alert("Please
upload a valid image file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FilePreview"
runat="server"
/>
<br />
<div id="ImagePreview"
style="width: 150px; height: 150px">
</div>
<asp:Button ID="btnSubmit"
runat="server"
Text="Upload"
/>
</div>
</form>
</body>
</html>
|
You can download the code by clicking on the below Download image.
Excellent Thanks Bro
ReplyDelete