Conventional File Upload In ASP.NET

This post is going to give some basic idea and common scenarios about the file uploading in ASP.NET. Mostly every data driven Website will provide this feature. Also, every ASP.NET developer faces this kind of requirement at least once in his/her developer life.

Note: The file upload control renders slightly/completely differently from one Browser to another Browser. If you want to give a consistent UI, you can check my previous post here. Also, you can read this article from my blog.

If you want to upload a file in ASP.NET, it is very simple. You need to include “File Upload” control on your form and place a command button, which triggers the upload process and saves the respective file in the specified location on the Server.

  1. <div>  
  2.     <asp:FileUpload runat="server" ID="fileUploader" AllowMultiple="false" /> <br />  
  3.     <asp:Button runat="server" Text="Upload" ID="btnUpload" OnClick="btnUpload_Click" />   
  4. </div>   

On the code at the backend, you should include the following:

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3.         if (fileUploader.HasFile)  
  4.         {  
  5.             fileUploader.SaveAs(Server.MapPath(@ "~\UploadedFile\")+ fileUploader.FileName);    
  6.         }      
  8. }     

Note: In the code snippet, given above, when you click the button, it will save the file in a specified location on the Server. As per the code, given above, it looks for the directory “UploadedFile” in the Server. Thus, you need to create the directory on your Application, before executing the code, otherwise the Application will throw an error, while running.

Upload specific File Types

In some cases, we may want to force the user to upload only the specific file types. This is an inevitable scenario for the professional programmers. In this case, we should validate the file types. If it passes, we can go with the upload. Otherwise, the user will be notified by an “error” message. In order to validate, I’m going to use the built-in ASP.NET validation control i.e. "Regular Expression Validator".

  1. <div>  
  2.     <asp:FileUpload runat="server" ID="fileUploadExcel" AllowMultiple="false" /> <br />  
  3.     <asp:Button runat="server" Text="Upload" ID="btnUploadExcel" OnClick="btnUploadExcel_Click" />  
  4.     <asp:RegularExpressionValidator runat="server" ControlToValidate="fileUploadExcel" ValidationExpression="^.*\.xls[xm]?$" ErrorMessage="Please upload excel file only"></asp:RegularExpressionValidator>  
  5. </div>   

The code at the backend has not changed much, compared to the previous one.

  1. protected void btnUploadExcel_Click(object sender, EventArgs e)  
  2. {  
  3.         if (fileUploadExcel.HasFile)  
  4.         {  
  5.            fileUploadExcel.SaveAs(Server.MapPath(@ "~\UploadedFile\") + fileUploadExcel.FileName);    
  6.         }  
  7. }   

Restrict Uploaded File Size

In some tedious cases, we need to restrict the file size. Say for example, we may need to force the user to upload MS Excel file, which is not more than 1 MB. In this case, we should validate this one from the Server, as shown below:

  1. protected void btnUploadExcel_Click(object sender, EventArgs e)  
  2. {  
  3. if (fileUploadExcel.HasFile)  
  4.   {  
  5.       int fileSize = fileUploadExcel.PostedFile.ContentLength;  
  6.       if (fileSize <= 1048576)  
  7.             fileUploadExcel.SaveAs(Server.MapPath(@"~\UploadedFile\") + fileUploadExcel.FileName);  
  8.        else  
  9.       {  
  10.             lblError.Text = "File size exceeds more than 1 MB.";  
  11.        }  
  12.    }  
  13. }  

Upload Multiple Files

In some cases, we may need to upload the multiple files. ASP.NET gives an easy way to achieve this. The file upload Server control had a property called “AllowMultiple”, which is a boolean value (either true or false). By turn, if it is true, the file upload control allows you to select the multiple files.

  1. <div>  
  2.     <asp:FileUpload runat="server" ID="fileUploadMultiple" AllowMultiple="true" /> <br />  
  3.     <asp:Button runat="server" Text="Upload" ID="btnUploadMultiple" OnClick="btnUploadMultiple_Click" />  
  4.     <asp:RegularExpressionValidator runat="server" ControlToValidate="fileUploadMultiple" ValidationExpression="^.*\.doc[x]?$" ID="RegularExpressionValidator1" ErrorMessage="Please upload word file only"></asp:RegularExpressionValidator>  
  5.     <asp:Label runat="server" ID="Label1" Style="color: red;"></asp:Label>  
  6. </div>   

In the code available at the backend, the code looks as given below. It gets the files, loops through the selected files and checks the file size. It stores it in the particular path.

  1. protected void btnUploadMultiple_Click(object sender, EventArgs e)  
  2. {  
  3.         if (fileUploadMultiple.HasFile)  
  4.         {  
  5.             HttpFileCollection files = Request.Files;  
  6.             for (int i = 0; i < files.Count; i++)  
  7.             {  
  8.                 HttpPostedFile file = files[i];  
  9.                 if (file.ContentLength > 0) fileUploadMultiple.SaveAs(Server.MapPath(@ "~\UploadedFile\") + file.FileName);    
  10.             }  
  11.         }  
  12.  }  
I hope this post gives some basic understanding and standard validations during the file upload in ASP.NET. Let me know your thoughts as comments.