Part 6 - How to upload files in the ASP.NET Web API using Http Client



Introduction

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

This post is 6th 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 Application (Client Application)

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

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

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

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

Right Click on Action Method (here right click on form action) > Add View... > Enter Name > Add.
View
@{
    ViewBag.Title = "Part6";
}

<h2>Part6 - Upload file to web api using Http Client</h2>
<div class="container">
    <div>
        @if (ViewBag.Success != null)
        {
            <div class="alert alert-success" role="alert">
                <strong>Well done !</strong> Successfully uploaded. <a href="@ViewBag.Success" target="_blank">open file</a>
            </div>
        }
        else if(ViewBag.Failed != null)
        {
            <div class="alert alert-error" role="alert">
                <strong>Error !</strong> @ViewBag.Failed
            </div>
        }
    </div>
    @using (Html.BeginForm("Part6","Home", FormMethod.Post,new{ role = "form", enctype="multipart/form-data"}))
    {
        <div class="form-group">
            <input type="file" id="file" name="file" />
        </div>
        <input type="submit" value="Submit" class="btn btn-default" />
    }
</div>
                    

Step-3: Add an another action for POST action for upload file to web api using HttpClient

[HttpPost]
public ActionResult Part6(HttpPostedFileBase file)
{
    using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            byte[] Bytes = new byte[file.InputStream.Length + 1];
            file.InputStream.Read(Bytes, 0, Bytes.Length);
            var fileContent = new ByteArrayContent(Bytes);
            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
            content.Add(fileContent);
            var requestUri = "http://localhost:1963/api/upload";
            var result = client.PostAsync(requestUri, content).Result;
            if (result.StatusCode == System.Net.HttpStatusCode.Created)
            {
                List<string> m = result.Content.ReadAsAsync<List<string>>().Result;
                ViewBag.Success = m.FirstOrDefault();

            }
            else
            {
                ViewBag.Failed = "Failed !" + result.Content.ToString();
            }
        }
    }
    return View();
}
                    

Step-4: Run Application.

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

Download Live Demo

Part 6 - How to upload files in the ASP.NET Web API using Http Client

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.