尝试用HttpPostedFileBase等文件对象作为参数获取上传内容,提示错误为:
"{"Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.","ExceptionMessage":"没有可用的 MediaTypeFormatter,无法从媒体类型为“multipart/form-data”的内容中读取类型为“HttpPostedFileBase”的对象。","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" 在 System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n 在 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}"
经查阅资料后判断API中无法使用该类对象作为参数,采用从HttpContext.Current.Request.Files中获取文件内容方式处理上传内容
/// <summary>
/// 单/多文件上传
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult UploadFileProc()
{
//从HttpContext.Current.Request.Files获取文件对象,如果存在内容则取第一个文件
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
//多文件时获取HttpContext.Current.Request.Files文件列表,并循环处理列表内容
// var files = HttpContext.Current.Request.Files.Count > 0 ?
//HttpContext.Current.Request.Files : null;
if (file != null && file.ContentLength > 0)
{
//获取文件名称
var fileName = Path.GetFileName(file.FileName);
string saveDir = HttpContext.Current.Server.MapPath("~/uploads");
if (!Directory.Exists(saveDir))//当保存路径不存在时创建
{
System.IO.Directory.CreateDirectory(saveDir);
}
//生成文件路径
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/uploads"),
fileName
);
file.SaveAs(path);//保存文件
return Json(path);
}
else {
return Json("");
}
}