Upload File Using Web API In ASP.NET MVC And jQuery

Here, we will learn about creating Web API in ASP.NET MVC and will also perform the file upload using Web API. Web API is very important in order to share data from the world.


  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of Web API
  • Basic knowledge of jQuery

Now, create a new project in ASP.NET Web Application and select the Web API framework when creating the project.


Now it will create a new Web API project in our application.

We will now add the new Web API controller. To create a new controller by right click on the controller folder.


Choose a Web API controller from it and name it as FileUploadApi.


Open the FileUploadApiController and add the code in it.

public class FileUploadApiController : ApiController
       public Task<HttpResponseMessage> Post()
           List<string> savedFilePath = new List<string>();
           if (!Request.Content.IsMimeMultipartContent())
               throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
           string rootPath = HttpContext.Current.Server.MapPath("~/Files");
           if (!Directory.Exists(rootPath))
           var pathProvider = new MultipartFileStreamProvider(rootPath);
           var newTask = Request.Content.ReadAsMultipartAsync(pathProvider).
               ContinueWith(task =>
                   if (task.IsCanceled || task.IsFaulted)
                       Request.CreateErrorResponse(HttpStatusCode.InternalServerError, task.Exception);
                   foreach (MultipartFileData item in pathProvider.FileData)
                           string fileName = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                           string newFileName = Guid.NewGuid() + Path.GetExtension(fileName);
                           File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
                           Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
                           string fileRelativePath = "~/Files/" + newFileName;
                           Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
                       catch (Exception ex) { }

                   return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
           return newTask;

Open the Index.cshtml file in the Home folder

    ViewBag.Title = "FileUpload";

    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;

    tr:nth-child(even) {
        background-color: #dddddd;

    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;

    .button4 {
        border-radius: 9px;


    <legend style="font-family:Arial Black;color:blue">Upload And Download Files Here</legend>
        <div class="form-group">
            <div id="updateStatus" class="alert" role="alert" style="display:none;"></div>
        <div class="col-md-12" style="text-align:center;margin-bottom:10px;">
            <input type="file" id="fileToBeUploaded" class="btn btn-primary" />
        <input id="btnUploadFile" class="button button4" type="button" value="Upload" />

    @section Scripts{
            $(document).ready(function () {
                $('#btnUploadFile').click(function () {
                    if ($('#fileToBeUploaded').val() == '') {
                        alert('Please select file');
                    var formData = new FormData();
                    var file = $('#fileToBeUploaded')[0];
                    formData.append('file', file.files[0]);
                        url: 'http://localhost:63350/api/fileuploadapi',
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (d) {
                            $('#updateStatus').addClass('alert-success').html('<strong>Upload Done!</strong><a href="' + d + '">Download File</a>').show();
                        error: function () {
                            $('#updateStatus').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();



Submit a Comment

Your email address will not be published.


Select Categories