How to send httppostedfile to webapi

How to host httppostedfile in webapi? Basically, I want the user to select the excel file, and I want to publish it on my website.

Gui was created using classic asp.net, and webapi was created using the new apicontroller.NET.

I already did some api encoding, but then used JSON, and it doesn't seem to work very well with this kind of object.

Can someone please just point me in the right direction so that I can continue to search for information. Right now I don’t even know what to look for.

+5
source share
1 answer

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.

+1
source

All Articles