Click here to Skip to main content
11,581,402 members (61,807 online)
Click here to Skip to main content

File Upload using jQuery AJAX in ASP.NET Web API

, 8 Sep 2014 CPOL 105.2K 6.3K 73
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.

You may also be interested in...

Comments and Discussions

 
Generalnice one Pin
Arkadeep De29-Jun-15 21:24
professionalArkadeep De29-Jun-15 21:24 
QuestionExcellent Article Pin
Kishor Khatri23-Mar-15 7:24
memberKishor Khatri23-Mar-15 7:24 
QuestionAn Awkward Technology simplified to a Breeze Pin
Member 817047913-Mar-15 22:51
memberMember 817047913-Mar-15 22:51 
Bugthe image not moving to the uploaded folder Pin
Member 105824232-Mar-15 22:17
memberMember 105824232-Mar-15 22:17 
QuestionFile Upload using jQuery AJAX in ASP.NET Web API Pin
Member 113959463-Feb-15 1:27
memberMember 113959463-Feb-15 1:27 
Generalnice Pin
Veera Saidarao27-Dec-14 1:16
memberVeera Saidarao27-Dec-14 1:16 
QuestionVB Version Pin
Dannweckl15-Dec-14 1:22
memberDannweckl15-Dec-14 1:22 
QuestionHow Can I Get The Current.Session? Pin
hector garduno18-Oct-14 14:48
grouphector garduno18-Oct-14 14:48 
Question5 vote Pin
bhagirathimfs25-Sep-14 1:21
memberbhagirathimfs25-Sep-14 1:21 
AnswerRe: 5 vote Pin
Dukhabandhu Sahoo25-Sep-14 5:52
professionalDukhabandhu Sahoo25-Sep-14 5:52 
Questionnice Pin
khem thapa22-Sep-14 22:42
memberkhem thapa22-Sep-14 22:42 
AnswerRe: nice Pin
Dukhabandhu Sahoo24-Sep-14 3:47
professionalDukhabandhu Sahoo24-Sep-14 3:47 
GeneralGood good Pin
Hussainp17-Sep-14 17:43
memberHussainp17-Sep-14 17:43 
GeneralRe: Good good Pin
Dukhabandhu Sahoo17-Sep-14 17:46
professionalDukhabandhu Sahoo17-Sep-14 17:46 
GeneralVote 5 Pin
Shemeemsha RA16-Sep-14 23:14
memberShemeemsha RA16-Sep-14 23:14 
GeneralRe: Vote 5 Pin
Dukhabandhu Sahoo17-Sep-14 2:33
professionalDukhabandhu Sahoo17-Sep-14 2:33 
Bugnice article..i indeed like it! Pin
ayaz adiyaman15-Sep-14 12:54
memberayaz adiyaman15-Sep-14 12:54 
GeneralRe: nice article..i indeed like it! Pin
Dukhabandhu Sahoo16-Sep-14 5:54
professionalDukhabandhu Sahoo16-Sep-14 5:54 
QuestionNot Working Remotely Pin
Member 263739310-Sep-14 4:44
memberMember 263739310-Sep-14 4:44 
AnswerRe: Not Working Remotely Pin
Dukhabandhu Sahoo10-Sep-14 5:39
professionalDukhabandhu Sahoo10-Sep-14 5:39 
QuestionHow to access posted file stream? Pin
M. Sreekanth8-Sep-14 23:00
memberM. Sreekanth8-Sep-14 23:00 
AnswerRe: How to access posted file stream? Pin
Dukhabandhu Sahoo9-Sep-14 3:47
professionalDukhabandhu Sahoo9-Sep-14 3:47 
GeneralRe: How to access posted file stream? Pin
M. Sreekanth9-Sep-14 19:52
memberM. Sreekanth9-Sep-14 19:52 
QuestionNicely composed Pin
Maninder Singh Puhi5-Sep-14 1:38
memberManinder Singh Puhi5-Sep-14 1:38 
AnswerRe: Nicely composed Pin
Dukhabandhu Sahoo8-Sep-14 3:59
professionalDukhabandhu Sahoo8-Sep-14 3:59 
QuestionMax file length? Pin
Akhil Mittal 4-Sep-14 18:20
mvp Akhil Mittal 4-Sep-14 18:20 
AnswerRe: Max file length? Pin
Anurag Gandhi8-Sep-14 2:12
professionalAnurag Gandhi8-Sep-14 2:12 
AnswerRe: Max file length? Pin
Dukhabandhu Sahoo8-Sep-14 4:03
professionalDukhabandhu Sahoo8-Sep-14 4:03 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan4-Sep-14 10:35
professionalAfzaal Ahmad Zeeshan4-Sep-14 10:35 
QuestionIt's useful Pin
Member 110268263-Sep-14 16:05
memberMember 110268263-Sep-14 16:05 
AnswerRe: It's useful Pin
Dukhabandhu Sahoo8-Sep-14 18:14
professionalDukhabandhu Sahoo8-Sep-14 18:14 
AnswerRe: It's useful Pin
Dukhabandhu Sahoo21-Jan-15 18:47
professionalDukhabandhu Sahoo21-Jan-15 18:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun2-Sep-14 18:22
memberHumayun Kabir Mamun2-Sep-14 18:22 
GeneralRe: My vote of 5 Pin
Dukhabandhu Sahoo9-Sep-14 0:41
professionalDukhabandhu Sahoo9-Sep-14 0:41 
QuestionProgressbar Pin
ayhantb1-Sep-14 20:15
memberayhantb1-Sep-14 20:15 
AnswerRe: Progressbar Pin
Dukhabandhu Sahoo2-Sep-14 4:08
professionalDukhabandhu Sahoo2-Sep-14 4:08 
GeneralMy vote of 5 Pin
ShaneFunng1-Sep-14 4:13
memberShaneFunng1-Sep-14 4:13 
GeneralRe: My vote of 5 Pin
Dukhabandhu Sahoo8-Sep-14 23:44
professionalDukhabandhu Sahoo8-Sep-14 23:44 
GeneralRe: My vote of 5 Pin
Dukhabandhu Sahoo22-Sep-14 23:39
professionalDukhabandhu Sahoo22-Sep-14 23:39 
QuestionFormatting issues Pin
Nelek31-Aug-14 22:43
memberNelek31-Aug-14 22:43 
AnswerRe: Formatting issues Pin
Dukhabandhu Sahoo31-Aug-14 23:18
professionalDukhabandhu Sahoo31-Aug-14 23:18 
GeneralRe: Formatting issues Pin
Nelek31-Aug-14 23:20
memberNelek31-Aug-14 23:20 
BugImages are not loading Pin
Vinay Mistry31-Aug-14 1:53
memberVinay Mistry31-Aug-14 1:53 
GeneralRe: Images are not loading Pin
Dukhabandhu Sahoo31-Aug-14 5:10
professionalDukhabandhu Sahoo31-Aug-14 5:10 
GeneralMy vote of 5 Pin
Burak Ozdiken30-Aug-14 2:44
memberBurak Ozdiken30-Aug-14 2:44 
GeneralRe: My vote of 5 Pin
Dukhabandhu Sahoo31-Aug-14 17:46
professionalDukhabandhu Sahoo31-Aug-14 17:46 

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 | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 8 Sep 2014
Article Copyright 2014 by Dukhabandhu Sahoo
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid