Introduction
In this post, I am going to explain Part 6 - How to upload files in the ASP.NET Web API using Http Client- Part1 - How to retrieve data from the database in the ASP.NET Web API using Jquery
- Part 2 - How to retrieve data from the database in the ASP.NET Web API using Http Client
- Part 3 - How to post data with validation in the ASP.NET Web API using Jquery
- Part 4 - How to post data with validation in the ASP.NET Web API using Http Client
- Part 5 - How to upload files in the ASP.NET Web API using Jquery
- Part 6 - How to upload files in the ASP.NET Web API using Http Client
- 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