ASP.NET MVC文件上传简单示例
一. 前端代码
Form 提交
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) {文件上传:"file" name="myFile"/>"submit" value="提交"/> }
Ajax 提交
上传文件: "zfiles" type="file" name="myFile" />
""; style="width:100px;height:100px;" id="imgs" /> "button" value="上传" onclick="test()" />
二. 后端代码
////// 上传文件 /// /// 上传文件结果信息 [HttpPost] public JsonResult UploadFile() { HttpPostedFileBase file = Request.Files["myFile"]; if (file != null) { try { //检查是否存在文件夹 string subPath = "D:\\pic"; if (false == System.IO.Directory.Exists(subPath)) { //创建pic文件夹 System.IO.Directory.CreateDirectory(subPath); } var filename = Path.Combine("D:\\pic", file.FileName); //Path.Combine(Request.MapPath("~/Upload"), file.FileName); MapPath:虚拟目录 file.SaveAs(filename); return Json("上传完成"); } catch (Exception ex) { return Json(string.Format("上传文件出现异常:{0}", ex.Message)); } } else { return Json("没有文件需要上传!"); } }