How to upload file with web-api
13,290
HTML Code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data">
<label for="somefile">File</label>
<input name="somefile" type="file" />
<input type="submit" value="Submit" />
</form>
Controller
// POST api/MyAPI
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.AllKeys[0] == "image")
{
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
try below link
this link use for me hopefully it will work you
http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
Related videos on Youtube
Author by
Ray
Updated on September 14, 2022Comments
-
Ray over 1 year
Client side code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data"> <label for="somefile">File</label> <input name="somefile" type="file" /> <input type="submit" value="Submit" /> </form>
And how to process upload file with mvc web-api,have some sample code?
-
vakeel over 8 yearsthanks kleopatra,shabeer90 for your valuable comment