FileUpload Validation for Images using RegularExpression


Code in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="FileUpload1"
ErrorMessage=".jpeg or .JPEG or .gif or .GIF or .png or .PNG Formats only"
ValidationExpression=
"(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpe?g|gif|png))(?:\?([^#]*))?(?:#(.*))?">
</asp:RegularExpressionValidator>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
style="font-weight: 700; color: #0000CC; background-color: #FFFF99"
Text="Upload" />
</form>
</body>
</html>

Code behind:

protected void Button1_Click(object sender, EventArgs e)
{
 if (FileUpload1.HasFile)
 {
     string str = FileUpload1.FileName;
     FileUpload1.PostedFile.SaveAs(MapPath("~/Uploads/" + str));
 }
}

DownloadSampleCode

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s