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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值