ASP.NET MVC文件上传简单示例
一. 前端代码
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) {文件上传:"file" name="myFile"/>"submit" value="提交"/> }
二. 后端代码
////// 上传文件 /// /// 上传文件结果信息 [HttpPost] public ActionResult 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 Content("上传完成"); } catch (Exception ex) { return Content(string.Format("上传文件出现异常:{0}", ex.Message)); } } else { return Content("没有文件需要上传!"); } }
原文:https://www.cnblogs.com/paopaotang/p/14962342.html