How to post file to ASP.NET Web Api 2
The simplest example would be something like this
[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/App_Data"));
var files = await Request.Content.ReadAsMultipartAsync(provider);
// Do something with the files if required, like saving in the DB the paths or whatever
await DoStuff(files);
return Request.CreateResponse(HttpStatusCode.OK);;
}
There is no synchronous version of ReadAsMultipartAsync
so you are better off playing along.
UPDATE:
If you are using IIS server hosting, you can try the traditional way:
public HttpResponseMessage Post()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string fileName in httpRequest.Files.Keys)
{
var file = httpRequest.Files[fileName];
var filePath = HttpContext.Current.Server.MapPath("~/" + file.FileName);
file.SaveAs(filePath);
}
return Request.CreateResponse(HttpStatusCode.Created);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}