Banner Ad

Tuesday, May 3, 2016

Conventional File Uploading in ASP.Net

By Francis   Posted at   5:12 PM   ASP.Net No comments
This post is going to give some basic ideas about file uploading in ASP.Net. Mostly every data driven web site will provide this feature. Also, every ASP.Net developer face this kind of requirement at least once in his/her developer life.



Note:
      The file upload control renders slightly/completely different from browser to browser. If you want to give a consistent UI, you can check my previous post here.

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 save the respective file in the specified location on the server.


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

On the code behind you should include the below lines:

protected void btnUpload_Click(object sender, EventArgs e)    
       {     
           if(fileUploader.HasFile)     
           {     
               fileUploader.SaveAs(Server.MapPath(@"~\UploadedFile\")+ fileUploader.FileName);     
           }     
       }     


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

Upload specific File Types:
In some cases, we may want to force the user 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 pass then we can go with 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.

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


The code behind not much changed compare to the previous one.

protected void btnUploadExcel_Click(object sender, EventArgs e)    
        {     
            if (fileUploadExcel.HasFile)     
            {     
                fileUploadExcel.SaveAs(Server.MapPath(@"~\UploadedFile\") + fileUploadExcel.FileName);     
            }     
        }

Restrict File Size:
In some cases, we need to restrict the file size. Say for example, we may need to force the user to upload an excel file not more than 1 MB. At this case, we should validate this one from the server as shown below:

protected void btnUploadExcel_Click(object sender, EventArgs e)    
      {     
          if (fileUploadExcel.HasFile)     
          {     
              int fileSize = fileUploadExcel.PostedFile.ContentLength;     
              if (fileSize <= 1048576)     
                  fileUploadExcel.SaveAs(Server.MapPath(@"~\UploadedFile\") + fileUploadExcel.FileName);     
              else     
              {     
                  lblError.Text = "File size exceeds more than 1 MB.";     
              }     
          }     
      } 

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

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

In the code behind, the code like below. It get the files and loop thru the selected files and check the file size then store it in the particular path.

protected void btnUploadMultiple_Click(object sender, EventArgs e)    
{     
    if (fileUploadMultiple.HasFile)     
    {     
        HttpFileCollection files = Request.Files;     
        for (int i=0;i < files.Count;i++)     
        {     
            HttpPostedFile file = files[i];     
            if(file.ContentLength >0)     
            fileUploadMultiple.SaveAs(Server.MapPath(@"~\UploadedFile\") + file.FileName);     
        }     
    }     
}    


I hope this post gives an some basic understanding and standard validations during the File upload in ASP.Net. Let me know your thoughts as comments. Happy Coding! Smile
Connect with Us