I solved this by doing the following: In my controller:
using (var client = new HttpClient()) using (var content = new MultipartFormDataContent()) { client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["PAM_WebApi"]); var fileContent = new ByteArrayContent(excelBytes); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; content.Add(fileContent); var result = client.PostAsync("api/Product", content).Result; }
And here is my ApiController:
[RoutePrefix("api/Product")] public class ProductController : ApiController { public async Task<List<string>> PostAsync() { if (Request.Content.IsMimeMultipartContent()) { string uploadPath = HttpContext.Current.Server.MapPath("~/uploads"); if (!System.IO.Directory.Exists(uploadPath)) { System.IO.Directory.CreateDirectory(uploadPath); } MyStreamProvider streamProvider = new MyStreamProvider(uploadPath); await Request.Content.ReadAsMultipartAsync(streamProvider); List<string> messages = new List<string>(); foreach (var file in streamProvider.FileData) { FileInfo fi = new FileInfo(file.LocalFileName); messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)"); } return messages; } else { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!"); throw new HttpResponseException(response); } } } public class MyStreamProvider : MultipartFormDataStreamProvider { public MyStreamProvider(string uploadPath) : base(uploadPath) { } public override string GetLocalFileName(HttpContentHeaders headers) { string fileName = headers.ContentDisposition.FileName; if (string.IsNullOrWhiteSpace(fileName)) { fileName = Guid.NewGuid().ToString() + ".xls"; } return fileName.Replace("\"", string.Empty); } }
I found this code in a tutorial, so I'm not the one to enroll. Therefore, I am writing a file to a folder. And because of mysreamprovider, I can get the same file name as the file that I first added to the GUI. I also add the end of the .xls file to the file because my program will only process excel files. So I added some input check in my GUI so that I know that the added file is an excel file.
source share