Showing posts with label How To Use RegularExpressionValidator with FileUpload control. Show all posts
Showing posts with label How To Use RegularExpressionValidator with FileUpload control. Show all posts

Monday, June 23, 2014

How To Use RegularExpressionValidator with FileUpload control

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadTest.aspx.cs" Inherits="FileUploadTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <table cellpadding="0" cellspacing="0" width="100%">
               <tr>
                   <td>
                       Select File</td>
                   <td>
                       <asp:FileUpload ID="fileUpload" runat="Server" /></td>
                   <td>
                       <td align="left">
                           <asp:RegularExpressionValidator runat="server" ID="valUpTest" ControlToValidate="fileUpload"
                               ErrorMessage="Image Files Only (.doc, .txt, .rtf)" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.rtf)$" />
                       </td>
                   </td>
               </tr>
               <tr>
                   <td colspan="2" align="Center">
                       <asp:Button ID="btnSubmit" runat="Server" Text="Submit" OnClick="btnSubmit_Click" />
                   </td>
               </tr>
           </table>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class FileUploadTest : System.Web.UI.Page
{
   string sPath = "Image";
   protected void Page_Load(object sender, EventArgs e)
   {

   }
   protected void btnSubmit_Click(object sender, EventArgs e)
   {
       if (fileUpload.HasFile)
       {


           fileUpload.PostedFile.SaveAs(Server.MapPath(sPath) + "/" + Path.GetFileName(fileUpload.PostedFile.FileName));

       }
   }

}