Part 5 - How to upload files in the ASP.NET Web API using Jquery


Introduction

In this post, I am going to explain Part 5 - How to upload files in the ASP.NET Web API using Jquery

This post is 5th part of a series called Getting Started with ASP.NET WEB API
  1. Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery
  2. Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
  3. Part 3 - How to post data with validation in the ASP.NET Web API using Jquery
  4. Part 4 - How to post data with validation in the ASP.NET Web API using Http Client
  5. Part 5 - How to upload files in the ASP.NET Web API using Jquery
  6. Part 6 - How to upload files in the ASP.NET Web API using Http Client
  7. Part 7 - How to retrieve and display data With Paging in the ASP.NET Web API using Jquery

Steps for Web API Application(Service)

Here in this example, the Web API application (service) is "WebApiExample".

Step-1: Add a folder in the WebApi application for save uploaded files

Go to solution explorer > Right click on Project Name(web api) > Add > New Folder > Rename folder (here I renamed "uploadFiles")

Step-2: Add a new controller in our WebApi application

Right click on controller folder (in web api application) > Add > Controller > Enter controller name > select "Empty API Controller" from Scaffolding options > Add.

Step-3: Add a new Action into the controller (in web api application) for upload 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 WebApiExample.Controllers
{
    public class UploadController : 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("~/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));
                            savedFilePath.Add(fileFullPath.ToString());
                        }
                        catch (Exception ex)
                        {
                            string message = ex.Message;
                        }
                    }

                    return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
                });
            return task;
        }
    }
}

                    

Steps for Web Application (Client Application)

Here in this example, the client application is "WebApiClient.Web".

Step-4: Add an Action to the HomeController (in MVC Client application) for get view for upload file.

                        public ActionResult Part5()
                        {
                            return View();
                        }
                    

Step-5: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.
View
<h2>Part5 - Upload files to the web api using jquery</h2>
<div>
    <div class="form-group">
        <div id="updatePanelFile" class="alert" role="alert" style="display:none;">

        </div>
    </div>
    <div class="form-group">
        <input type="file"  id="file1"/>
    </div>
    <input id="btnPostFile" class="btn btn-default" type="button" value="Upload" />
</div>
                    

Step-6: Add following jquery for upload file to web api

<script>
    $(document).ready(function () {
        $('#btnPostFile').click(function () {
            if ($('#file1').val() == '') {
                alert('Please select file');
                return;
            }

            var formData = new FormData();
            var file = $('#file1')[0];
            formData.append('file', file.files[0]);
            $.ajax({
                url: 'http://localhost:1963/api/Upload',
                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();
                    $('#file1').val(null);
                },
                error: function () {
                    $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();
                }
            });
        });
    });
</script>
                    
Complete View
@{
    ViewBag.Title = "Part5";
}

<h2>Part5 - Upload files to the web api using jquery</h2>
<div>
    <div class="form-group">
        <div id="updatePanelFile" class="alert" role="alert" style="display:none;">

        </div>
    </div>
    <div class="form-group">
        <input type="file"  id="file1"/>
    </div>
    <input id="btnPostFile" class="btn btn-default" type="button" value="Upload" />
</div>

@section Scripts{
    <script>
        $(document).ready(function () {
            $('#btnPostFile').click(function () {
                if ($('#file1').val() == '') {
                    alert('Please select file');
                    return;
                }

                var formData = new FormData();
                var file = $('#file1')[0];
                formData.append('file', file.files[0]);
                $.ajax({
                    url: 'http://localhost:1963/api/Upload',
                    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();
                        $('#file1').val(null);
                    },
                    error: function () {
                        $('#updatePanelFile').addClass('alert-error').html('<strong>Failed!</strong> Please try again.').show();
                    }
                });
            });
        });
    </script>
}

                    

Step-7: Run Application.

Here we need to start both application as the client application will consume services from web api application.

Download Live Demo


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.