Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Wednesday, 4 February 2015

Introduction
In this article we will learn how to restrict users to upload the files of specific type through FileUpload control by validating through RegularExpressionValidator validation control.

Description: 
Sometimes it is required to validate the file extension before uploading the  file i.e. you want that user can upload only the files of specific extension e.g. if you want the user can upload only Word  and Excel  files(.doc, .docx, .xls, .xlsx ) then you have to check the extension of the file the user is going to upload. Similarly if you want only images of the type (.png, .jpg, .jpeg, .bmp or.gif) can be uploaded then it is also possible.


Implementation: 
Let's create an asp.net website to understand.

  • Place a FileUpload control and the RegularExpressionValidator control , ValidationSummary control and a Button Control on design page(.aspx)
  <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Only excel or word file is allowed!"
ValidationExpression ="^.+(.xls|.XLS|.xlsx|.XLSX|.doc|.DOC|.docx|.DOCX)$"
ControlToValidate="FileUpload1"
Display="None">
 </asp:RegularExpressionValidator>

<asp:ValidationSummary ID="ValidationSummary1" runat="server"
            ShowMessageBox="True" ShowSummary="False" />

<asp:Button ID="btnUpload" runat="server"  Text="upload"
            onclick="btnUpload_Click" />


C#.Net Code to check and validate file extension before uploading a file

  • In the code behind (.aspx.cs) file write the code:
    protected void btnUpload_Click(object sender, EventArgs e)
    {
            //write code to upload file
            string filePath = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(filePath);
    }

VB.Net Code to check and validate file extension before uploading a file

  • In the code behind (.aspx.vb) file write the code:
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)     
                                         'write code to upload file
                                         Dim filePath As String = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName)
                                         FileUpload1.SaveAs(filePath)                   
End Sub


Note:  If you want to upload only image files e.g. .png,.jpg,.jpeg,.bmp or gif then write ValidationExpression ="^.+(.png|.jpg|.jpeg|.bmp|.gif|)$".

In this example Uploaded file will be saved in the Uploads folder. Create a folder in your website and use that folder to save Images or files.

0 comments:

Post a Comment