This product was discontinued

How to upload files in ASP.NET

Nowadays you may find file upload in almost every website – from forums that allow users to upload photos for their avatars, to online auctions where users can create galleries with a lot of images. The chief thing is that file upload should be fast, easy, and reliable.

There are a number of different upload approaches in ASP.NET. Thus, it is essential to choose the one that suits your requirements best: whether it is uploading a few files one by one or multiple files at a time, working with files of small or very large size, sending entire folders or files only, having a simple image upload or preprocessing images beforehand.

In this article we consider different ways of file upload in ASP.NET and discuss their use, but before let’s see how file upload works in general.

Files Upload Basics

The upload process is quite simple. There are always two parts, the client and server sides, that communicate with each other through HTTP requests and responses. Let’s consider the usual upload scenario:

  1. A user visits a web page and chooses files to upload.
  2. The client application packs these files to a POST request and sends it to the server.
  3. The server parses the request, handles it (for example, saves files on a hard disk), and sends a response to the client side.

You can design a client side using different components: ASP.NET or HTML controls, HTML5, Flash, Java, or ready-to-use upload applications. We will discuss them below.

Now let’s examine how the server works.

When the HTTP request is received, ASP.NET starts the uploading process: it caches all data in server memory or to disk depending on the uploaded file size.

After all files are uploaded, the server code runs. Here is where you can handle uploaded data, for example: save the uploaded files to the appropriate location, examine their characteristics, update a database, etc.

Using ASP.NET you don’t need to parse the HTTP request manually, you just refer to the uploaded files through the HttpPostedFile collection. This makes life easier, because all you need is to iterate through each file in this collection and perform the necessary actions.

When the server code execution is finished, the server cleans up the memory and sends an HTTP response to the client.

You can configure your ASP.NET application by editing the web.config (or machine.config if you want to change settings globally, for all ASP.NET applications on your server). There are several attributes in the <httpRuntime> section which are important for the file upload:

  • maxRequestLength – the request size limit in kilobytes (the default value is 4096 KB).
  • requestLengthDiskThreshold – the limit of data buffered in the server memory in kilobytes (the default value is 80 KB).
  • executionTimeout – the allowed execution time for the request before being automatically shut down by ASP.NET (the default value is 110 seconds).

Note: it is not recommended specifying very large (virtually unlimited) values as it may lead to the risk of DoS attacks.

We’ve figured out the files upload organization in ASP.NET, now it is time to examine different upload approaches. Let’s start with the simplest one – using the standard ASP.NET FileUpload control.

Using FileUpload Control

FileUpload supports single and multiple file uploads. It allows a user to choose a file to be uploaded via the Browse button. The control doesn’t automatically save a selected file to the server, but it exposes the SaveAs method to perform this. Deploying FileUpload in your web application is very easy. Firstly, let’s discuss how to do it for uploading a single file at a time.

Single File Upload

To add single file upload functionality in your website just embed the FileUpload control to the <form> tag in the place where you want users to display the upload interface. The code may look as follows:

<html>              
    <head>
        <title>Upload Files</title>
    </head>
<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br/>
        <asp:Button ID="UploadButton" runat="server" 
                    OnClick="UploadButton_Click"
                    Text="Upload File" />
        <br/>
        <asp:Label ID="FileUploadedLabel" runat="server" />
    </form>
</body>
</html>

After running this page, you will see the following interface:

Simple file upload form in ASP.NET

Let’s highlight the difficult parts:

  1. The FileUpload control (like any other server control) needs to be included in the <form> tag.
  2. The form should have the runat=”server” attribute, which indicates that the form is processed on the server and the FileUpload control can be accessed by server scripts.
  3. The form should also contain id, name, and method attributes. Typically they are automatically generated by ASP.NET.
  4. The onClick attribute of the Upload File button specifies the event handler that processes file upload.

After a user clicks the Upload File button, the form data will be sent to the server. The code of the Upload File button click handler should look like this:

protected void UploadButton_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)            
        try
        {
            FileUpload1.SaveAs(Server.MapPath("~/uploads/") +
                 FileUpload1.FileName);
            FileUploadedLabel.Text = "File name: " +
                 FileUpload1.PostedFile.FileName + "<br>" +
                 FileUpload1.PostedFile.ContentLength + " kb<br>" +
                 "Content type: " + FileUpload1.PostedFile.ContentType;
        }
        catch (Exception ex)
        {
            FileUploadedLabel.Text = "ERROR: " + ex.Message.ToString();
        }
    else
    {
        FileUploadedLabel.Text = "You have not specified a file.";
    }
}

This event handler checks if any file has been specified, tries to save it to the uploads folder, and displays a message indicating whether the file has been saved successfully. Note that the FileUpload1 name is similar to the FileUpload id attribute in the client form discussed above.

When adding simple upload to you web application do not forget that it does not protect your server from the malicious files that a user can upload. There are several security concerns which can help you to consider whether accept an uploaded file. For example, you can control the type of uploaded file by checking the extension (which can be easily spoofed) or the correct "magic number" in the file header.

To upload a single file at a time is very easy, but it in rare use nowadays. If you are going to design your own site, most likely you will need to upload several files at a time. So, let’s see how you can do it.

Multiple Files Upload

The most important advantage of the FileUpload server control is the support of multiple file upload. To enable it, just slightly modify the client application considered above. However, you should understand that the multiple upload feature works correctly only in browsers that support HTML5.

The only change required in the client application considered above is adding the AllowMultiple property which specifies whether multiple files can be selected for upload:

<html>
<head>
    <title>Upload Files</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="FilesUpload" runat="server" 
                        AllowMultiple="true" />
        <br/>
        <asp:Button ID="UploadButton" runat="server" 
                    OnClick="UploadButton_Click"
                    Text="Upload File" />
        <br/>
        <asp:Label ID="FileUploadedList" runat="server"/>
    </form>
</body>
</html>

The code behind the Upload File button also needs to be modified: before saving a file, the UploadButton_Click event handler should iterate through all uploaded data. Now the handler code may look as follows:

protected void UploadButton_Click(object sender, EventArgs e)
{
    if (FilesUpload.HasFile)
        foreach (HttpPostedFile uploadedFile in FilesUpload.PostedFiles)
            try
            {
                uploadedFile.SaveAs(Server.MapPath("~/uploads/") + 
                                    uploadedFile.FileName);
                FileUploadedList.Text += "File name: " +
                   uploadedFile.FileName + "<br>" +
                   uploadedFile.ContentLength + " kb<br>" +
                   "Content type: " + uploadedFile.ContentType + "<br><br>";
            }
            catch (Exception ex)
            {
                FileUploadedList.Text = "ERROR: " + ex.Message.ToString();
            }
    else
    {
        FileUploadedList.Text = "You have not specified a file.";
    }
}

As a result, you will get the same upload interface, but the text box displays the number of selected files:

Multiple file upload form for ASP.NET

The FileUpload control is great when you only upload a few small files, but it has several disadvantages: 

  1. There is no opportunity to display uploading progress.
  2. Uploading a large number of files is very inconvenient, because the page does not respond while the file upload is processed.
  3. If a browser does not support HTML5, it won’t work at all.
  4. Every browser displays it in a different way.

Fortunately, some third party uploaders are partially free of these concerns. Let’s discuss them.

Third Party File Uploaders

Nowadays all popular browsers support the Flash or newer HTML5 platform, which allows the creating of advanced file upload using Flex or JavaScript respectively. Thus, there are a lot of third-party uploaders. The most popular are open source HTML5/Flash-based uploaders, for example:

  • Uploadify is a jQuery plugin with a queue of files that are not uploaded yet, a real-time progress bar for each file, custom upload limitation, etc.
  • Fine Uploader is a JavaScript plugin tool with multiple file selection, progress bar, auto and manual upload, image preview, etc.
  • Plupload is an upload tool based on several platforms, which even includes some image processing functionality, etc.

These uploaders are very good at multiple file upload, provide a simple interface, and are supported by a big community of developers. However, the following tasks cannot be solved by these uploaders:

  • Preprocessing uploaded images (resize, crop, rotate, generate thumbnails, add watermarks, etc.).
  • Uploading entire folders and keeping a folder’s structure on the server.
  • Uploading a large amount of files.
  • Large files upload (of hundreds MB or even several GB).
  • Automatic restore of the broken uploads.
  • Speeding up the upload process.

All these scenarios are ideal for Aurigma’s Upload Suite. You can do it with few lines of code.

See how to get started

Get a free 30-day trial

Upload Suite includes premium uploaders based on various technologies (HTML5, Flash, Java, ActiveX) for any server technology – ASP.NET and PHP, classic ASP and JSP, Ruby-on-rails and node.js.