天天看點

FileUpload filter

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

[ Back To Top ]

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
           
            
        
FileUpload filter
"></asp:FileUpload> <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click"   Text="Upload"></asp:Button> 
Client Side Approach

[ Back To Top ]

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

[ Back To Top ]

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

繼續閱讀