New Document
ASP.NET - File Uploading

ASP.Net has two controls that allow the users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it or ignore it. The following controls allow the file uploading:


Back in the ASP world, uploading files via a web page was a tricky problem. The problem was that due to the encryption type of the form used to submit the file from the client's browser, receiving such files on the server side was a complex task. Data had to be retrieved as a safe byte array and decrypted before it could be used. Most of the people resorted to 3rd party DLLs. A few wrote their own DLLs and some even wrote purely ASP solutions to this problem using VBScript. Fortunately for us, the .NET Framework SDK comes with a few classes that make uploading of the files simple from the web developer point of view. This article will demonstrate following concepts:

  • HtmlInputFile - an HTML server control

  • FileUpload - and ASP.Net web control

The requirements for an HTML form to be able to upload files are very simple: you have to use multipart/form-data encryption and you have to use method of post. Collapse | Copy Code

< form id="Form1" method="post" runat="server" enctype="multipart/form-data">

HTML input control that is used to upload file has a simple type of file.

Collapse | Copy Code

< input id="filMyFile" type="file" runat="server">
This is all that needs to be done to an HTML form for a client to be able to submit a file to your ASP.NET application.

< INPUT TYPE="file" corresponds to the System.Web.UI.HtmlControls.HtmlInputFile type of object on the server side. So if you, like myself, are using a CodeBehind architecture for your page you will have a member field definition similar to this in your class:

Collapse | Copy Code


protected HtmlInputFile filMyFile;

HtmlInputFile classes have a few different properties, but the only one that really concerns us here is PostedFile. This property will tell us all we need to know about the file that had been uploaded to our server. The PostedFile property is null if no file was submitted by a client. So, we can simply check whether a file was sent by doing something like this:

Collapse | Copy Code


if( filMyFile.PostedFile != null )
{
    // File was sent

}
else
{
    // No file

}

The PostedFile property will contain a valid System.Web.HttpPostedFile object if file indeed was uploaded.

HttpPostedFile provides us with 4 properties:


ContentLength: size of uploaded file in bytes

ContentType: MIME type of uploaded file, i.e. "image/gif"

FileName: full path to uploaded file on client's system, i.e. c:\Some folder\MyPicture.gif

InputStream: stream object that gives us access to uploaded data

Both the controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.

In this tutorial, we will use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a Browse button and a text box for entering the filename.

Once, the user has entered the filename in the text box, by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.

When using the File Field control in ASP.NET 1.x you had to take a few extra steps to get everything in line and working. For example, you were required to add enctype="multipart/form-data" to the page's

element on your own. The new FileUpload server control provided in ASP.NET 2.0 makes the process of uploading files to the hosting server as simple as possible.


In the end, you are trying to allow access to program the HTML < input type="file"> tag. This tag is used to work with file data within an HTML form. In the past when using classic ASP (ASP 3.0 or earlier), many programmers worked with third-party components to upload files from the client to the server. Now, with .NET and this new control, uploading is taken care of for you. Listing 1 shows you how to use the FileUpload control to upload files to the server.


The basic syntax for using the FileUpload is:

<asp:FileUpload ID= "Uploader" runat = "server" />

The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:

PropertiesDescription
FileBytesReturns an array of the bytes in a file to be uploaded..
FileContentReturns the stream object pointing to the file to be uploaded.
FileNameReturns the name of the file to be uploaded.
HasFileSpecifies whether the control has a file to upload.
PostedFileReturns a reference to the uploaded file.

The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.

The HttpPostedFile class has the following important properties, which are much used:

PropertiesDescription
ContentLengthReturns the size of the uploaded file in bytes.
ContentTypeReturns the MIME type of the uploaded file
FileNameReturns the full filename.
InputStreamReturns a stream object pointing to the uploaded file.

Example:

The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type and file length.

In the design view, the form looks like:

File Upload

The content file:

<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
   <asp:FileUpload ID="FileUpload1" runat="server" />
   <br /><br />
   <asp:Button ID="btnsave" runat="server" 
               onclick="btnsave_Click" Text="Save" 
               Width="85px" />
   <br /><br />
   <asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>

The code behind the save button:

protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   if (FileUpload1.HasFile)
   {
      try
      {
      sb.AppendFormat(" Uploading file: {0}", 
                                  FileUpload1.FileName);
      //saving the file
      FileUpload1.SaveAs("<c:\\SaveDirectory>" + 
                                  FileUpload1.FileName);
      //Showing the file information
      sb.AppendFormat("<br/> Save As: {0}", 
                         FileUpload1.PostedFile.FileName);
      sb.AppendFormat("<br/> File type: {0}",   
                         FileUpload1.PostedFile.ContentType);
      sb.AppendFormat("<br/> File length: {0}", 
                         FileUpload1.PostedFile.ContentLength);
      sb.AppendFormat("<br/> File name: {0}", 
                         FileUpload1.PostedFile.FileName);
      }
      catch (Exception ex)
      {
      sb.Append("<br/> Error <br/>");
      sb.AppendFormat("Unable to save file <br/> {0}", 
                         ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}

Note the following:

  • The StringBuilder class is derived from System.IO namespace, so it should be included.

  • The try and catch blocks are used for catching errors, and display the error message.



Previous                                                                                                                                                       Next

Back to Top