Click here to Skip to main content
15,860,861 members
Articles / Web Development / ASP.NET

File Upload using jQuery AJAX in ASP.NET Web API

Rate me:
Please Sign up or sign in to vote.
4.78/5 (66 votes)
8 Sep 2014CPOL5 min read 417.4K   14.3K   94   61
Simple way to upload file using jQuery AJAX in ASP.NET Web API

Introduction

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.

    Image 1

  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.

    Image 2

  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.

    Image 3

  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".

    Image 4

    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 the below screenshot:

    Image 5

    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".

    Image 6

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

    C#
    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:
    C#
    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.
    C#
    [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 assigned 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.

    Image 7

    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.

    HTML
    <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:
    HTML
    <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.

    JavaScript
    <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 a 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.

    C#
    // 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 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:

XML
<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 Value: 30000000 bytes (~29 MB)

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

History

  • 8th September, 2014: Initial version

License

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


Written By
Software Developer (Senior)
India India
I have developed web applications using ASP.NET Web Forms, MVC, Web API, Entity Framework, SQL Server, LINQ, C#, jQuery, BootStrap UI and few other related libraries and tools.

Apart from programming, I love to watch cricket matches.

Comments and Discussions

 
Questionwhic is not sending any image or file to server side Pin
incobilgisayar23-Dec-19 2:24
incobilgisayar23-Dec-19 2:24 
AnswerIt works Pin
Marcos Jeremias Davissone Junior4-Oct-18 21:59
Marcos Jeremias Davissone Junior4-Oct-18 21:59 
Questionsave image into folder and database its path from web service asmx file c# Pin
Member 116024221-Jan-18 20:58
Member 116024221-Jan-18 20:58 
QuestionThis really Help Pin
katlegoEmmnanuelNkosi17-Jun-17 22:00
katlegoEmmnanuelNkosi17-Jun-17 22:00 
Questionpost detail and file using ajax post using asp.net webMethod Pin
Vikash Vishwakarma 1224915016-Nov-16 20:40
Vikash Vishwakarma 1224915016-Nov-16 20:40 
QuestionAppreciate the information Pin
Member 125757809-Jun-16 16:32
Member 125757809-Jun-16 16:32 
QuestionMission Impossible Pin
Member 1225069215-Jan-16 0:38
Member 1225069215-Jan-16 0:38 
QuestionHow to handle the file size? Pin
Jeevanandan J31-Oct-15 5:33
Jeevanandan J31-Oct-15 5:33 
QuestionNice Pin
charbaugh7-Oct-15 10:56
charbaugh7-Oct-15 10:56 
QuestionFile Upload using jQuery AJAX in ASP.NET Web API Pin
Member 1033240522-Aug-15 1:07
Member 1033240522-Aug-15 1:07 
Generalnice one Pin
Arkadeep De29-Jun-15 21:24
professionalArkadeep De29-Jun-15 21:24 
QuestionExcellent Article Pin
Kishor Khatri23-Mar-15 7:24
Kishor Khatri23-Mar-15 7:24 
QuestionAn Awkward Technology simplified to a Breeze Pin
Member 817047913-Mar-15 22:51
Member 817047913-Mar-15 22:51 
Bugthe image not moving to the uploaded folder Pin
Member 105824232-Mar-15 22:17
Member 105824232-Mar-15 22:17 
GeneralRe: the image not moving to the uploaded folder Pin
Member 111588373-Mar-16 8:29
Member 111588373-Mar-16 8:29 
GeneralRe: the image not moving to the uploaded folder Pin
Member 111588374-Mar-16 9:51
Member 111588374-Mar-16 9:51 
QuestionFile Upload using jQuery AJAX in ASP.NET Web API Pin
Member 113959463-Feb-15 1:27
Member 113959463-Feb-15 1:27 
Generalnice Pin
Veera Saidarao27-Dec-14 1:16
Veera Saidarao27-Dec-14 1:16 
QuestionVB Version Pin
Dannweckl15-Dec-14 1:22
Dannweckl15-Dec-14 1:22 
QuestionHow Can I Get The Current.Session? Pin
hector garduno18-Oct-14 14:48
hector garduno18-Oct-14 14:48 
Question5 vote Pin
bhagirathimfs25-Sep-14 1:21
bhagirathimfs25-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
khem 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
Hussainp17-Sep-14 17:43 

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

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