今儿查了好多关于webapi接收前台同时传来的参数和文件,这一通查找啊,把谷歌百度都翻烂了,找了一堆乱七八糟的,和大家分享下。
好多人们是这样做的
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
// 检查该请求是否含有multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
// 读取表单数据
await Request.Content.ReadAsMultipartAsync(provider);
// 显示所有“键-值”对
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
//Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}
// This illustrates how to get the file names.
// 以下描述如何获取文件名
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
这让我一通看才看明白,而且上面还是整理完他们代码过后的
后来自己找到了比较好的方法,如下
public IHttpActionResult getTest2()
{
string id=HttpContext.Current.Request["id"];
string name = HttpContext.Current.Request["name"];
HttpFileCollection files = HttpContext.Current.Request.Files;
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];//file.ContentLength文件长度
if (string.IsNullOrEmpty(file.FileName) == false)
file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/") + file.FileName);
}
return Ok("success2");
}
简单明了,共享之,希望对大家有帮助。