Reputation: 19329
I want to simply upload a file to server using WebAPI. I want to call the WebApi in my MVC HomeController. When I use the WebAPI directly it uploads files perfectly however when I want to call the WebAPI within my Controller using PostAsync, it does not send the file to the api for some reason.
This is the action in my MVC Controller:
public async Task<ActionResult> Upload(HttpPostedFileBase upload)
{
ViewBag.Title = "Upload Files";
if (upload != null && upload.ContentLength > 0)
{
var client = new HttpClient();
string FullUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + ":" + Request.Url.Port + "/api/values";
StringContent httpcontent = new StringContent(upload.FileName);
var response = await client.PostAsync(FullUrl, httpcontent);
var result = await response.Content.ReadAsAsync<HttpResponseMessage>();
}
return View();
}
This is the .cshtml file:
<form name="form1" method="post" action="/Home/Upload" enctype="multipart/form-data">
<div>
<label for="upload">Choose a File</label>
<input name="upload" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
Finally this is the WebApi Controller:
[HttpPost]
public HttpResponseMessage PostFile()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
Upvotes: 1
Views: 4228
Reputation: 639
When content post by the form, it's setup multipart/form-data content type to the request. You can try to setup request content type to multipart/form-data explicitly.
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(upload.InputStream);
fileContent.Headers.ContentType = upload.ContentType;
requestContent.Add(fileContent, upload.FileName, upload.FileName);
client.PostAsync(url, requestContent);
Upvotes: 2