web api文件上传

public IHttpActionResult ConfirmUpload()
{
HttpFileCollection files = HttpContext.Current.Request.Files;
if (files != null)
{
try
{
foreach (string key in files.AllKeys)
{
if (files[key].FileName != "")
{
HttpPostedFile file = files[key];
//string exName = Path.GetExtension();
string uploadPath = ConfigurationManager.AppSettings["FoodPath"].ToString();
if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));
}
#region 大图保存
var fileName =Path.GetFileName(file.FileName);//解决IE和Google中file上传(是否带本地物理路径)
string pattern = "[\\[ \\] \\^ \\-_*×――(^)$%~!@#$…&%¥—+=<>《》!!???::•`·、。,;,;\"‘’“”-]";//过滤特殊字符
fileName = Regex.Replace(fileName, pattern, "_");

var filePath = (uploadPath + fileName).Replace(@"/", @"\");
string tmpRootDir = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath.ToString());
string fileSavePath = tmpRootDir + filePath;
//文件存在即删除
if (File.Exists(fileSavePath))
{
File.Delete(fileSavePath);
}
file.SaveAs(fileSavePath);

return Json(new { path = filePath, success = true, content = "上传图片成功!" });
}
}
}
catch (Exception e)
{
return Json(new { success = false, content = e.Message });
}
}
return Json(new { success = false, content = "未找到文件!" });

}

 

posted @ 2019-09-27 17:05  艺洁  阅读(691)  评论(0编辑  收藏  举报