参考资料
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2
代码实现
[HttpPost]
public async Task<HttpResponseMessage> UploadExcel()
{
/*
* 方法一:
*/
var result = await Request.Content.ReadAsMultipartAsync();
var requestJson1 = await result.Contents[0].ReadAsStringAsync();
var requestJson2 = await result.Contents[1].ReadAsStringAsync();
var requestJson3 = await result.Contents[2].ReadAsStringAsync();
var requestJson4 = await result.Contents[3].ReadAsStringAsync();
//接收转Json
var request = JsonConvert.DeserializeObject<List<Subjects>>(requestJson4);
/*
* 方法二:
*/
var requestJson4 = await result.Contents
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
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));
}
}
//获取文件数据
if (HttpContext.Current.Request.Files.Count > 0)
{
var file=HttpContext.Current.Request.Files[0];
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
return Request.CreateResponse(HttpStatusCode.OK);
}