Loading, please wait...

A to Z Full Forms and Acronyms

File Upload in ASP.NET Web API Using jQuery AJAX

I will explain how to upload file on server in ASP.NET Web API using jQuery AJAX call. I have to create post method in API Controller

Introduction:

Today in this article, I will explain How to upload files in ASP.NET Web API using jQuery. In this example, I have added the uploaded file’s content to the Form Data’s collection by jQuery. If you are beginner in ASP.NET Web API, Refer below post for basics of Web API

Follow these steps in order to implement “File upload in Web API using jQuery AJAX”

 

Step1: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC Web Application > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select Web API > then click to ok

 

 

 

Step2: Create API service for save uploaded file on Server.

By default “ValuesController” API Controller is added, I have to add the method for save file into this API Controller.

 

 

Firstly we have to add a new folder “UploadFiles” to the solution explorer.

Add the below code to the ValuesController for save the uploaded file.

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Threading.Tasks;

using System.Web;

using System.Web.Http;



namespace WebAPIFileUpload.Controllers

{

    public class ValuesController : ApiController

    {

        public Task<HttpResponseMessage> uploadfile()

        {

            List<string> savefilepath = new List<string>();

            if (!Request.Content.IsMimeMultipartContent())

            {

                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            }

            string rootpath = HttpContext.Current.Server.MapPath("~/UploadFiles");

            var provider = new MultipartFileStreamProvider(rootpath);

            var task = Request.Content.ReadAsMultipartAsync(provider).

                ContinueWith<HttpResponseMessage>(t =>

               {

                   if (t.IsCanceled || t.IsFaulted)

                   {

                       Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);

                   }

                   foreach (MultipartFileData item in provider.FileData)

                   {

                       try

                       {

                           string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");

                           string newfilename = Guid.NewGuid() + Path.GetExtension(name);

                           File.Move(item.LocalFileName, Path.Combine(rootpath, newfilename));



                           Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));

                           string fileRelativePath = "~/UploadFiles/" + newfilename;

                           Uri filefullpath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));

                           savefilepath.Add(filefullpath.ToString());

                       }

                       catch (Exception)

                       {



                           throw;

                       }

                   }

                   return Request.CreateResponse(HttpStatusCode.Created, savefilepath);

               });

            return task;

        }

    }

}

 

Above code uses the “POST” method. If the user posts any file then it will save that file on the server and return the full path of the file. If there is no posted file then it returns the exception details.

 

Step3: Add View to upload the file.

Go to HomeController > Right Click on Action Method > Add View > Enter View Name > Select View Engine (Razor) > Add. (Here I add Index view)

Now write the following code:

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script>

    $(function () {

        $('#btnupload').click(function () {

            debugger;

            if ($('#fileupload').val()=='') {

                alert('Plase select file');

                return;

            }

            var formdata = new FormData();

            var file = $('#fileupload')[0];

            formdata.append('file', file.files[0]);



            $.ajax({

                url: 'http://localhost:30944/api/values/uploadfile',

                type: 'POST',

                data: formdata,

                contentType: false,

                processData: false,

                success: function (d) {

                    $('#updatepanelFile').addClass('alert-success').html('<strong>Success!</strong><a href="' + d + '">Open File</a>').show();

                },

                error: function () {

                    $('#updatepanelFile').addClass('alert_error').html('<strong>Failed!</strong> Error in upload');

                }

            })

        });

    });

</script>



<div class="row">

    <div class="col-sm-12">

        <div class="form-group">

            <div id="updatepanelFile" class="alert" role="alert" style="display:none"> </div>

        </div>

        <div class="form-group">

            <input type="file"  id="fileupload"/><br />

          <input type="button"  value="upload" id="btnupload" class="btn btn-default"/>

        </div>

    </div>

</div>

 

In above code, I have created the jQery AJAX method for post file on the server. I take a  “formdata” variable and append the posted file to that variable. When file saved successfully on the server then add URL of the image to attribute in "updatepanelFile" div. If the file is not saved then it's throwing the error.

 

Step 4: Run Application.

We have done all steps, Now It’s time to run the application

A to Z Full Forms and Acronyms