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

Part 6 - Upload file to web api using Http Client
Part 6 - How to upload files in the ASP.NET Web API using Http Client
using Entities; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Mvc; namespace WebApiClient.Web.Controllers { public class HomeController : Controller { public ActionResult Part1() { return View(); } public ActionResult Part2() { List<Employee> list = new List<Employee>(); HttpClient client = new HttpClient(); var result = client.GetAsync("http://localhost:1963/api/Example").Result; if (result.IsSuccessStatusCode) { list = result.Content.ReadAsAsync<List<Employee>>().Result; } return View(list); } public ActionResult Part3() { return View(); } public ActionResult Part4() // for save data using httpclient { return View(); } [HttpPost] public ActionResult Part4(Employee emp) { if (ModelState.IsValid) { HttpClient client = new HttpClient(); var result = client.PostAsJsonAsync("http://localhost:1963/api/Example", emp).Result; if (result.IsSuccessStatusCode) { emp = result.Content.ReadAsAsync<Employee>().Result; ViewBag.Result = "Successfully saved!"; ModelState.Clear(); return View(new Employee()); } else { ViewBag.Result = "Error! Please try with valid data."; } } return View(emp); } public ActionResult Part5() { return View(); } public ActionResult Part6() { return View(); } [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(); } } } 
 
Posted By :