I bet that most of you have faced this common problem: “How to upload large size files (above 4MB) in ASP.NET?”  As you know, the default maximum file size allowed in the framework is 4MB and this is to prevent service attacks like submitting large files, which can overwhelm the server resources. In this blog post I am going to show you how to overcome this limitation, as well as how to validate the file size and type on the client before submitting it to the server.

Uploading large files in ASP.NET – the solution:

All it takes to overcome the framework limitation is to do several modifications to the project’s web.config file. To enable large file uploads you need to change the value of the following attributes on the system.web/httpRuntime configuration element:

  • maxRequestLength: Specifies the limit for the input stream buffering threshold in KB and allows you to control the allowed total size of the upload. Anything bigger than that will result in the default for the framework "Page not found" error.
  • ExecutionTimeout: Specifies the maximum number of seconds for which a request is allowed to be executed before being automatically shut down by ASP.NET – the default time is 110 seconds. If the request takes longer to be executed, an exception will be thrown.
  • maxAllowedContentLength (IIS 7) - specifies the maximum length of content in a request supported by IIS. By default it restricts the content length to 30,000,000 bytes. 

For example, the web.config configuration allowing uploads of files up to 100MB and upload periods of up to 1 hour should look like the following:

<configuration>
 
...
 
<system. web>
 
<httpRuntime maxRequestLength="102400" executionTimeout="3600" />
 
...
 
</system .web>
 
</configuration>

If you use IIS7 and you want to upload files larger than the restricted 30000000 bytes or 28.6 MB, you can add the following code to your web.config file in order to set that value to 100 MB:

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="104857600" />
        </requestFiltering>
    </security>
</system.webServer>

Validating the File Type and Size

Sometimes you want to limit the file type and size which the user is allowed to upload on the server. This might be related to the application’s security or overall performance.

Here are some validation options you can choose from:

Using the ASP File Upload control

The main disadvantage of the standard file upload control is that it does not offer client-side validation. Therefore the file needs to first be uploaded to the server and then validated by some custom implementation of such functionality. Here is a simple server-side validation scenario involving the ASP File Upload control:

//markup code
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button runat="server" ID="btnUpload" Text="Upload" OnClick="btnUpload_Click" />

//code behind
protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile file = fileUpload.PostedFile;
        if ((file != null) && (file.ContentLength > 0))
        {
            if (IsImage(file) == false)
            {
                // Invalid file type
                return;
            }
        }
        int iFileSize = file.ContentLength;
 
 
        if (iFileSize > 1048576)  // 1MB
        {
            // File exceeds the file maximum size
            return;
        }
 
        // validation passed successfully
    }
 
 
    private bool IsImage(HttpPostedFile file)
    {
        //Checks for image type... you could also do filename extension checks and other things
        return ((file != null) && System.Text.RegularExpressions.Regex.IsMatch(file.ContentType, "image/\\S+") && (file.ContentLength > 0));
    }

Using an HTML5 Input and File API in Modern Browsers

The File API comes with the new web standard HTML5 and is supported by all modern browsers. Its main advantages are that it offers client-side validation and additionally supports the following features:

  • Multiple file upload
  • Stand-alone progress monitoring (No http module used!)
  • Support for the same events as the other modules
  • Upload cancellation
  • Upload files via chunks, effectively walking around the ASP.NET max files size limitation.
  • File type and size validation on the client side.
The sample code below shows how powerful the File API could be in accessing the selected files on the client side and how to perform a custom validation:
<input id="image-file" type="file" name="file" />

<script type="text/javascript">
  
    //this code will be executed when a new file is selected
    $('#image-file').bind('change', function () {
  
        //converts the file size from bytes to MB
        var fileSize = this.files[0].size / 1024 / 1024;
  
        //gets the full file name including the extension
        var fileName = this.files[0].name;
  
        //finds where the extension starts
        var dotPosition = fileName.lastIndexOf(".");
  
        //gets only the extension
        var fileExt = fileName.substring(dotPosition);
  
        //checks whether the file is .png and less than 1 MB
        if (fileSize <=  1 && fileExt == ".png") {
  
           //successfully validated
  
        }
    });
</script>

Custom JavaScript Code for Non-modern Browsers

So what happens when you want to validate uploaded files in browsers which don’t support HTML5? The most common solution for validating the file type in such case is to use a custom JavaScript code and for validating the file size - to use the approach for server-side validation described above.  A sample scenario would look like this:

<input id="image-file" type="file" name="file" />

<script type="text/javascript">
  
    //this code will be executed when a new file is selected
    $('#image-file').bind('change', function () {
  
        //gets the full file name including the extension
         var fileName = this.value;
  
        //finds where the extension starts
        var dotPosition = fileName.lastIndexOf(".");
  
        //gets only the extension
        var fileExt = fileName.substring(dotPosition);
  
        //checks whether the file is .png
        if (fileExt == ".png") {
  
           //successfully validated
  
        }
    });
</script>

Other options: using Silverlight, Flash or IFrame plugins

Of course there are some additional options to choose from if your browser does not support the HTML5 File API and you want to avoid writing a custom JavaScript code. You can simply use the Adobe Flash or Silverlight plugin.  They are available for download and install though your browser Add-on manager.

Let’s explain a bit about each of the modules:

Flash & IFrame Modules

The IFrame and Flash modules upload the selected file(s) using normal http post request. The IFrame uses <input type="file" /> tag for file uploads, whereas Flash uses the Flex object in order to upload files.

It is very important to know that the Flash module allows you to validate both file type and size on the client side.  The files are uploaded using Post HTTP request in absolutely the same manner as the normal <input type="file" />. Since both modules upload a file with a single request, in case of uploading a file larger than the 4MB ASP.NET default limitation, you need to modify your web.config file as shown in the first section. 

Browser support: IE9,8,7.

Silverlight Module

In contrast, the Silverlight upload is designed in a different way so that it divides the file to be uploaded on the client side in many chunks, each of which is 2MB large. It then starts uploading the chunks one after another subsequently. It does support file type and size validation on the client.

Browser support: Firefox  < 3.6, IE9,8,7.

There’s an easier way to upload and validate files

If you’re using a third-party control, such as Telerik’s Asynchronous ASP.NET upload control, all of the above modifications will be taken care of for you.

RadAsyncUpload is working with modules based on the above information in order to handle the upload process no matter of the current browser version. The module with highest priority is File API. If the browser does not support File API, the module is automatically changed to Silverlight. If there is no Silverlight installed on the client machine, RadAsyncUpload will utilize the Flash module. If neither Flash nor Silverlight are installed – the IFrame module takes place.

RadAsyncUpload helps you overcome the 4 MB file size upload limitation in ASP.NET by dividing the large files into smaller chunks and uploading them subsequently. You can control the size of the chunks and thus the number of requests to the server required to upload the file, which can improve your application's performance. No need to modify the configuration file and override different properties.

Just set the ChunkSize property to the desired value and you are ready to go!

<telerik:RadAsyncUpload runat="server" ID="AsyncUpload1" ChunkSize="1048576" />

If you wonder how to monitor the change in the number of requests to the server, when you change the size of the chunks – the Telerik web debugging tool Fiddler could quickly do that for you:



What we have done so far:

After reading this article you should now be able to:

  • Implement custom server-side validation for your uploaded files with the standard ASP.NET File Upload control in order to prevent any service attacks submitting large files.
  • Validate the selected files on the client only by using HTML 5 File API and a single input field on the page.
  • Implement a custom JavaScript code to check the file name on the client when working with browsers which do not support HTML5.
  • Understand different options and modules required based on the client browser in order to upload a file successfully to the server.
 Please feel free to comment below if you know other or easier ways to accomplish the things described above.

 

    Telerik ASP.Net AJAX Controls - Download a trial version
    About the Author

    Boyan Dimitrov

     is a Support Officer at Telerik’s ASP.NET AJAX Division, where he is mainly responsible for RadScheduler and the navigation controls. He joined the company in 2012 and ever since he has been working on helping customers with various RadControls scenarios and improving the online resources. Boyan’s main interests are the web, mobile and client-side programming. In his spare time he likes participating in sport activities, walking in the nature and reading criminal stories. 

    Google Profile

    Related Posts

    Comments