Adding Filter Action to FileUpload Control of ASP.NET 2.0
 
Published: 03 Apr 2008
Abstract
In this article, Soyuj explains the logic to implement the ASP.NET 2.0 FileUpload Control for adding the ability to filter files. After a brief introduction, he discusses both the client and server side approaches with the help of source code. At the end of the article Soyuj also provides a few useful references to learn more about the discussed topic.
by Soyuj Kumar Sahoo
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 78122/ 50

Introduction

When we need to Upload any file in to our system we need the Browse and Upload action. In the case of Windows application of .NET there is a control called OpenFileDialog which is used for Uploading any file with browsing. Here we can get the file filter action by using the Filter property. For example, we have to Upload only the test files into our system, so we can set the filtering action as: (OpenFileDialog)Object.Filter = "Text files|*.txt; *.doc; *.rtf" in Windows Application of .NET.

So, when windows developers need this type of filtering action in Web Application, they have a option of using asp:FileUpload control of ASP.NET. Unfortunately, we which have no such property to set a filter for doing the file filtering action before Uploading. So we need to develop our own logic to achieve our Objective.

To get the filtering action we have two options in Web Application:  Client side action and Server side action. In this article we will discuss both the possible ways with a step-by-step example to add the file filtering logic in our application.

Add FileUpload Control

Before discussing the two approaches, add the following two controls in your aspx page if these were not added earlier.

Listing 1: Add FileUpload Control

<asp:FileUpload ID="fileDocument" runat="server"></asp:FileUpload>
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click"  
Text="Upload"></asp:Button> 
Client Side Approach

For any client side action we have to choose a scripting language to build our logic. Let us go for JavaScript. When use a file control we have to use a button control for doing the uploading action. It is better to refer to Anand's article CodeSnip: Working with FileUpload Control to get the basic idea of using FileUpload control.

Then at the button Client event we have to add some JavaScript action to do the filtering action. We have to use the "OnClientClick" event of a <asp:Button /> control. The code is given below.

Listing 2: OnClientClick

<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload"
Width="64px" OnClientClick="return CheckForTestFile();" />

Now our objective is to put the filtering logic in CheckForTestFile() JavaScript function. For this action, copy and paste the following code inside your <HEAD> tag of aspx page.

Listing 3: JS Filter function

<script language="javascript">  
  //Trim the input text
  function Trim(input)
  {
    var lre = /^\s*/; 
    var rre = /\s*$/; 
    input = input.replace(lre, ""); 
    input = input.replace(rre, ""); 
    return input; 
   }
 
   // filter the files before Uploading for text file only  
   function CheckForTestFile() 
   {
        var file = document.getElementById('<%=fileDocument.ClientID%>');
        var fileName=file.value;        
        //Checking for file browsed or not 
        if (Trim(fileName) =='' )
        {
            alert("Please select a file to upload!!!");
            file.focus();
            return false;
        }
 
       //Setting the extension array for diff. type of text files 
       var extArray = new Array(".txt", ".doc"".rtf"".pdf"".sxw", ".odt", 
                                ".stw", ".html"".htm"".sdw"".vor");       
 
       //getting the file name
       while (fileName.indexOf("\\") != -1)
         fileName = fileName.slice(fileName.indexOf("\\"+ 1);
 
       //Getting the file extension                     
       var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();
 
       //matching extension with our given extensions.
       for (var i = 0; i < extArray.length; i++) 
       {
         if (extArray[i] == ext) 
         { 
           return true;
         }
       }  
         alert("Please only upload files that end in types:  " 
           + (extArray.join("  ")) + "\nPlease select a new "
           + "file to upload and submit again.");
           file.focus();
           return false;                
   }    
</script>

Let us go through the codes. The Trim() function would trim the input text. Therefore, in the above code we first check whether there is any file selected in FileUpload control or not. Then we parse the file name with the path to the file-name of the input file using the slice() method of JavaScript which takes the index as input. After getting the file we will still continue parsing to get the file extension out from the File name. Then we iterate a loop to match the input extension with the defeat extensions of our interest stored in an array. If the input extension does not match with any one of the given extension,s we show the alert message and return false as status. This does not allow us to Upload the file and give us a alert message to fetch a file with the given extensions.

Server Side Approach

In the btnUpload_Click() event of "btnUpload" we have to add the following code, which will check the maximum size of the file and also filter the extension.

Listing 4: Server side filter action

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
 Handles btnUpload.Click
Try
Dim intDocFileLength As Integer = Me.fileDocument.PostedFile.ContentLength
Dim strPostedFileName As String = Me.fileDocument.PostedFile.FileName
 
If intDocFileLength > 4096000 Then '4MB
  Me.lblUploadErr.Text = "Image file size exceeds the limit of 4000 kb."
  Exit Sub
End If
 
If (strPostedFileName <> String.Empty) Then
  Dim strExtn As String = System.IO.Path.GetExtension(strPostedFileName).ToLower
 
  If (strExtn = ".txt"Or (strExtn = ".doc"Or (strExtn = ".rtf"Or _
     (strExtn = ".pdf"Or (strExtn = ".sxw"Or (strExtn = ".odt"Or _
     (strExtn = ".html"Or (strExtn = ".stw"Or (strExtn = ".htm"Or _
     (strExtn = ".sdw"Or (strExtn = ".vor"Then
 
    Dim savePath As String = _
      Server.MapPath(ConfigurationManager.AppSettings("UploadedPath")) & "\"
 
    Me.fileDocument.PostedFile.SaveAs(savePath & _
                                      System.IO.Path.GetFileName(strPostedFileName))
 
    Me.lblUploadErr.Text = "Document uploaded successfully..."
  Else
    Me.lblUploadErr.Text = _
      "Please upload a valid Document with the extenion in : <br>"
    Me.lblUploadErr.Text + = _
      ".txt, .doc, .rtf, .pdf, .sxw, .odt, .stw, .html, .htm, .sdw Or .vor"
  End If
Else
  Me.lblUploadErr.Text = "There is no file to Upload."
End If
Catch ex As Exception
'TODO: Add the Error log entry logic!
End Try
End Sub

Let us move through the codes. The fileDocument.PostedFile.ContentLength property of FileUpload control will give the size of the posted file as bytes and the fileDocument.PostedFile.FileName property will give the file name of the posted one. Then we check for the maximum size which is fixed to 4 MB as 4096000 bytes here. Then we get the file extension using the System.IO.Path.GetExtension() method of the input file. We match the posted extension with our given extensions. If the match satisfies, we do the Uploading action or else we show the error message in label.

References

Conclusion

The above two approaches can be implemented either one or both at a time. Both the approaches have their own merits and demerits. In the case of Client side approach, the JavaScript should be enabled in the Client's browser; in the case of Server side approach, we have to make an extra server loop. So, it is upon you to choose which one is suitable to your application.

By Soyuj Kumar Sahoo



User Comments

Title: Adding Filter Action to FileUpload Control of ASP.NET 2.0   
Name: shivesh
Date: 2012-12-13 2:13:51 AM
Comment:
One of the best client side validations i have seen
Title: Fipe Upload Control   
Name: Roland Hentschel
Date: 2012-10-17 5:23:44 AM
Comment:
Hi,

sorry, but I'm really dumb for using ASP.
Couldn't you provide a zipped example ?
Would really like to be able to check the size of a file,
before it is uploaded, that also works in IE <= v9

regards ( -: roland .- )
Title: Thank You   
Name: omar ali
Date: 2012-07-10 5:29:27 AM
Comment:
Thank You
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-05-20 11:39:29 PM
Comment:
[/pre]Cheap NFL,NBA,MLB,NHL
[url=http://www.jersey2shop.com/]Jerseys From China[/url]
[url=http://www.jersey2shop.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jersey2shop.com/]cheap China Jerseys[/url]
[url=http://www.jersey2shop.com/]Sports Jerseys China[/url]
[url=http://www.jersey2shop.com/NFL-Jerseys-c68/]NFL Jerseys China[/url]
[url=http://www.jersey2shop.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
NHL Jerseys China
[url=http://www.jersey2shop.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]We Are Professional China jerseys Wholesaler
[url=http://www.cheapjersey2store.com/]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url= http://www.cheapjersey2store.com/]2012 mlb all atar jerseys[/url]
[url= http://www.cheapjersey2store.com/ [/url]Cheap China Wholesael[/url]
[url= http://www.cheapjersey2store.com/]Wholesale jerseys From China[/url]
[url=http://www.cheapjersey2store.com/]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.cheapjersey2store.com/]Jerseys From China[/url]
[url=http://www.cheapjersey2store.com/NFL-Jerseys-c68]NFL jerseys China[/url]
[url=http://www.cheapjersey2store.com/NHL-Jerseys-c96/]NHL Jerseys China[/url]
[url=http://www.cheapjersey2store.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
[url=http://www.cheapjersey2store.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]
[url= http://www.cheapjersey2store.com/]China Jerseys[/url],Free Shipping
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.jerseycaptain.com/]cheap jerseys sale online [/url]
[url= http://www.jerseycaptain.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jerseycaptain.com/NFL-Jerseys-c68]cheap NFL jerseys China[/url]
[url=http://www.jerseycaptain.com/NHL-Jerseys-c96/]NHL Jerseys C
Title: HELP   
Name: sean
Date: 2012-01-13 4:29:49 PM
Comment:
I was expecting that when I click on Browse button, It will list only different type of text files as specified. can it be done???? please help
Title: vajinismus   
Name: vajinismus
Date: 2011-10-12 10:45:41 AM
Comment:
thanks..
Title: ZIP File cause no validation   
Name: user
Date: 2011-06-23 12:37:52 PM
Comment:
If i select zip it straight away cause my page error :(
Title: Not Working   
Name: Phani337
Date: 2010-01-11 4:41:42 AM
Comment:
Hey man.Before posting just do unit testing.In the array list JPEG ext is not there.But when i am uploading the jpeg file it is simply uploading with out showing any alert message.
Title: Thats a bad way of identifying files   
Name: Mike
Date: 2009-06-15 4:20:42 AM
Comment:
You really shouldn't be using the file extension as an identifier to the type of file. Use the MIME type.
Title: Thanks Buddy!   
Name: Ajinkya
Date: 2009-05-23 12:39:11 AM
Comment:
I think This article is very usefull fou me!
Title: I have a idear   
Name: wwvww
Date: 2009-04-26 6:10:49 AM
Comment:
string fileName=fu.FileName;//fu is a entity of FileUpload
private string GetFileType()
{
return this.fileName.Substring(this.fileName.LastIndexOf("."), this.fileName.Length - this.fileName.LastIndexOf("."));
}
if(GetFileType()!=".doc")
{
HttpContext.Response.Write("please upload the .doc file");
}
Title: What I want is a propertity name of Filer   
Name: wwvww
Date: 2009-04-26 6:01:20 AM
Comment:
the js is too long to read,do you have another better idear?
Title: Please i want FIlter   
Name: Vishakha
Date: 2009-02-23 11:40:58 PM
Comment:
I was expecting that when I click on Browse button, It will list only different type of text files as specified
".xls", ".doc", ".rtf", ".pdf", ".html", ".htm", ".sdw", ".vor"

Where as I am getting various other files too.
I expect it would filter initially and should not validate after it is selected.
Title: There is not any kind of filter i seen,   
Name: Manish
Date: 2009-02-03 1:03:32 AM
Comment:
I was expecting that when I click on Browse button, It will list only different type of text files as specified
".txt", ".doc", ".rtf", ".pdf", ".sxw", ".odt", ".stw", ".html", ".htm", ".sdw", ".vor"

Where as I am getting various other files too.
I expect it would filter initially and should not validate after it is selected.

Thanks
manishwc@gmail.com
Title: How to retrieve File date info?   
Name: NP
Date: 2008-08-14 10:12:15 PM
Comment:
Is there a way to retrieve last modified or created dates for file using the file upload control? I use file upload control to mainly get the file bytes and use it to store file contents in database.
However, my requirement is also to have original file date from client side and to store it in database. I am unable to get the date stamp from client side
Appreciate any help.
Title: File Upload Issue   
Name: Rekha
Date: 2008-07-28 1:37:35 AM
Comment:
Hi..
When I click on the Browse button the Choose File dialog should open in thumbnail view always.. Is this possible and if yes then how?
Pls help
Title: Thanks   
Name: b@2te
Date: 2008-07-22 2:42:06 AM
Comment:
Thanks
Title: Good   
Name: Mr.6
Date: 2008-07-01 2:38:23 AM
Comment:
this article is very good.
Title: Good article   
Name: Mehul Bhuva
Date: 2008-04-09 6:53:20 AM
Comment:
It is a nice article..Keep it up
Title: Excellent Work   
Name: ali raza
Date: 2008-04-08 7:40:38 AM
Comment:
nice article, keep working
Title: File Filters   
Name: Haissam Abdul Malak
Date: 2008-04-03 2:00:41 AM
Comment:
Good article. However, you can use flash and ASP.NET to set the file filters on the open dialog box itself and to upload multiple files at one.
http://dotnetslackers.com/community/blogs/haissam/archive/2008/03/29/upload-multiple-files-using-asp-net-amp-adobe-flex.aspx

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 7:55:53 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search