客户端代码:
<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>
如何使用mvc web-api处理上传文件,有一些示例代码?
答案 0 :(得分:1)
HTML代码:
<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>
<强>控制器强>
// 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;
}
尝试以下链接
这个链接对我有用,希望它对你有用
http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
答案 1 :(得分:0)
您可以使用ApiMultipartFormFormmatter将文件上传到网络API 2。 通过使用此库,您可以定义视图模型以获取从客户端提交的参数。如:
public class UploadFileViewModel
{
public HttpFile Somefile{get;set;}
}
并在你的Api控制器中使用它:
public IHttpActionResult Upload(UploadFileViewModel info)
{
if (info == null)
{
info = new UploadFileViewModel();
Validate(info);
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok();
}
此库可以解析嵌套对象。