Click here to Skip to main content
Click here to Skip to main content
Go to top

File Upload using jQuery AJAX in ASP.NET Web API

, 8 Sep 2014
Rate this:
Please Sign up or sign in to vote.
Simple way to upload file using jQuery AJAX in ASP.NET Web API.

Upload file using jQuery AJAX in ASP.NET Web API

This article provides an easy way to upload an image file using jQuery AJAX in ASP.NET Web API. 

Upload Idea: 

The idea here is to add the uploaded file's content to the FormData's collection by jQuery and in the action/method get the posted file's content from the Files' collection by a key.

In the next walk-through I will show how to add a Web API controller to an empty ASP.NET web application and how the file will be posted through jQuery AJAX to the controller's action.

Steps

1. Add an empty ASP.NET Web application as follows. The below mentioned walk-through for this demo application is created by using Visual Studio 2013.

From Visual Studio click "New Project" and then from the Templates tab select Visual C#. From the list of template categories, select ASP.NET Web Application. Provide a name for the web application and click the "OK" button.

2. The next window will ask for the type of ASP.NET Web Application template you want to apply. Choose "Empty" and click "OK" button. It will create an empty web application which will contain packages.config and Web.config files.  

3. Now let's add the "Global.asax" file which is essential for an ASP.NET Web Application. Right click on the Project in Visual Studio and select Add -> New Item. It will display the "Add New Item" window as follows. Choose "Global Application Class" file from the list as highlighted below.

4. Then we have to add the ASP.NET Web API package to the project. To do so, right-click on the project in Visual Studio and select "Manage Nuget Packages".

It will display the "Manage Nuget Packages" window and from the left side select "Online" tab and search for "Microsoft.AspNet.WebApi". The results will be similar to below screenshot: 

Select "Microsoft ASP.NET Web API 2.2" and click the "Install" button. Note that the version of the Web API may vary as when the article was written the latest available version was 2.2. After the package is downloaded if it will ask for license acceptance click "I Accept" button. 

You can install the Web API nuget package from the Package Manager Console(View -> Other Windows -> Package Manager Console) by using the following command:

Install-Package Microsoft.AspNet.WebApi

It will install the latest Web API package to the project.

5. Now we have successfully installed the Web API package. Let's add a simple class which will act as the controller. It will contain an action i.e method which will handle the file upload.

Right click on the project in Visual Studio and select Add -> Class. Name it like "FileUploadController.cs". By convention, all the controller class file names are suffix with "controller".

Now go to "FileUploadController.cs" class file and inherit it from "ApiController". Every ASP.NET Web API controller files are inherited from this "ApiController".

public class FileUploadController : ApiController

6. We have added the controller. We need to register a route for this controller. For that, go to "Global.asax.cs" file and register a route like follows:

GlobalConfiguration.Configure(config =>
{
     config.MapHttpAttributeRoutes();

     config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
          );
});

Here the {controller}, {action} and {id} are the keywords for the route. The Web API controller is registered with a route where the path is prefixed with "/api". 

7. Let's add an action i.e method inside "FileUploadController.cs" file which will handle the file upload operation.

[HttpPost]
public void UploadFile()
{
    if (HttpContext.Current.Request.Files.AllKeys.Any())
    {
       // Get the uploaded image from the Files collection
       var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

       if (httpPostedFile != null)
       {
	   // Validate the uploaded image(optional)

	   // Get the complete file path
           var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);

	    // Save the uploaded file to "UploadedFiles" folder
	    httpPostedFile.SaveAs(fileSavePath);
	}
     }
}

The UploadFile() method/action is only accessible by POST request as it is assiged with [HttpPost] attribute. 

The uploaded files are saved to "UploadedFiles" folder. You can add an empty folder by right-clicking on the project and select Add -> New Folder.

8. Let's add an ".aspx" page which will upload the file. right-click on the project -> Add -> New Item 

From the "Add New Item" window select "Web Form" and give a name for it. Set the newly added ".aspx" page as start page for the project. To do so, right-click on the ".aspx"page and select "Set As Start Page" option from the context menu.

Let's add the HTML controls i.e for this case add a file upload control and a button. The file upload control will browse the file which will be uploaded on button click.

<div><label for="fileUpload">Select File to Upload: <input id="fileUpload" type="file" />

<input id="btnUploadFile" type="button" value="Upload File" /></div>

9. Now we are left with only one change i.e adding jQuery code to save the file content to FormData's collection. First let's add a reference to jQuery from Google CDN library as follows:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

The code shown next adds the file content to FormData's collection.

<script type="text/javascript">
$(document).ready(function () {

   $('#btnUploadFile').on('click', function () {

      var data = new FormData();

      var files = $("#fileUpload").get(0).files;

      // Add the uploaded image content to the form data collection
      if (files.length > 0) {
           data.append("UploadedImage", files[0]);
      }

      // Make Ajax request with the contentType = false, and procesDate = false
      var ajaxRequest = $.ajax({
           type: "POST",
           url: "/api/fileupload/uploadfile",
           contentType: false,
           processData: false,
           data: data
           });

      ajaxRequest.done(function (xhr, textStatus) {
                    // Do other operation
             });
   });
});
</script>

Here we are making an jQuery AJAX request to UploadFile() action of FileUploadController.cs file with path "/api/fileupload/uploadfile". 

Note: The contentType and processData is set to false which is important.

You can see the uploaded content is added to the FormData's collection with key "UploadedImage" which is also used to retrieve the uploaded file's content inside the UploadFile() action.

// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

Now run the application and from the "FileUploadTest.aspx" page(it may vary if you have given other name in step #8) you can a upload file. 

This idea can also be applied to ASP.NET MVC Controller to upload a file by jQuery AJAX.

How to change the size limitation to upload large files?

If you want to upload large file(maximum 2 GB!) then you need to change the <httpRuntime> and <requestLimits> default settings in Web.config file like follows:

<system.web>
  <httpRuntime executionTimeout="240000" maxRequestLength="2147483647" />
</system.web>

<security>
  <requestFiltering>
    <requestLimits maxAllowedContentLength="4294967295"/>
  </requestFiltering>
</security>

executionTimeout

It is the maximum number of seconds a request is allowed to execute before being automatically shut down by ASP.NET. The value is in seconds

Default Value: For ASP.NET 1.x it is 90 seconds and for ASP.NET 2.0 or higher it is 110 seconds.

Maximum Value: Theoretically its maximum value is the maximum value of TimeSpan i.e 10675199.02:48:05.4775807. The value of this setting is ignored in debug mode.

maxRequestLength 

It is the maximum allowed request length. The value is in K.B(Kilo Bytes)

Default Value: 4 MB

Maximum Value: Theoretically its maximum value is the maximum value of int i.e 2147483647.

maxAllowedContentLength

It specifies the maximum length of content in a request. The value is in bytes.

Default Value30000000 bytes(~29 MB)

Maximum Value: Theoretically its maximum value is the maximum value of uint(unsigned interger) i.e 4294967295.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dukhabandhu Sahoo
Software Developer Mindfire Solutions
India India
I have been working with ASP.NET Web Technology for 3+ years.
 
I have developed web applications which uses ASP.NET Web Forms, Web API, Entity Framework, SQL Server, LINQ, C#, jQuery, BootStrap UI and few other related libraries and tools.
 
Apart from programming, I spend time in watching cricket matches.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
Question5 vote Pinmemberbhagirathimfs25-Sep-14 1:21 
AnswerRe: 5 vote PinprofessionalDukhabandhu Sahoo25-Sep-14 5:52 
Questionnice Pinmemberkhem thapa22-Sep-14 22:42 
AnswerRe: nice PinprofessionalDukhabandhu Sahoo24-Sep-14 3:47 
GeneralGood good PinmemberHussainp17-Sep-14 17:43 
GeneralRe: Good good PinprofessionalDukhabandhu Sahoo17-Sep-14 17:46 
GeneralVote 5 PinmemberShemeemsha RA16-Sep-14 23:14 
GeneralRe: Vote 5 PinprofessionalDukhabandhu Sahoo17-Sep-14 2:33 
Bugnice article..i indeed like it! Pinmemberayaz adiyaman15-Sep-14 12:54 
GeneralRe: nice article..i indeed like it! PinprofessionalDukhabandhu Sahoo16-Sep-14 5:54 
QuestionNot Working Remotely PinmemberMember 263739310-Sep-14 4:44 
AnswerRe: Not Working Remotely PinprofessionalDukhabandhu Sahoo10-Sep-14 5:39 
QuestionHow to access posted file stream? PinmemberM. Sreekanth8-Sep-14 23:00 
AnswerRe: How to access posted file stream? PinprofessionalDukhabandhu Sahoo9-Sep-14 3:47 
GeneralRe: How to access posted file stream? PinmemberM. Sreekanth9-Sep-14 19:52 
QuestionNicely composed PinmemberManinder Singh Puhi5-Sep-14 1:38 
AnswerRe: Nicely composed PinprofessionalDukhabandhu Sahoo8-Sep-14 3:59 
QuestionMax file length? Pinmvp Akhil Mittal 4-Sep-14 18:20 
AnswerRe: Max file length? PinprofessionalAnurag Gandhi8-Sep-14 2:12 
AnswerRe: Max file length? PinprofessionalDukhabandhu Sahoo8-Sep-14 4:03 
GeneralMy vote of 5 PinprofessionalAfzaal Ahmad Zeeshan4-Sep-14 10:35 
QuestionIt's useful PinmemberMember 110268263-Sep-14 16:05 
AnswerRe: It's useful PinprofessionalDukhabandhu Sahoo8-Sep-14 18:14 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun2-Sep-14 18:22 
GeneralRe: My vote of 5 PinprofessionalDukhabandhu Sahoo9-Sep-14 0:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 8 Sep 2014
Article Copyright 2014 by Dukhabandhu Sahoo
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid