1.单个文件上传
HTML写法:form表单中加enctype="multipart/form-data"
1 <form aciont="" method="post" enctype="multipart/form-data"> 2 <input type="file" id="file" name="file" /> 3 <br/> 4 <input type="submit" name="提交"/> 5 </form>
View写法:同样 form表单中加enctype="multipart/form-data"
1 @using (Html.BeginForm("Add", null, FormMethod.Post, new { enctype = "multipart/form-data" })) 2 { 3 <input type="file" id="file" name="file" /> 4 <br/> 5 <input type="submit" value="提交"/> 6 }
后台Controller中的写法:
1 [HttpPost] 2 public ActionResult Add(HttpPostedFileBase file) 3 { 4 string path = "/uploadImg/"; 5 if (!Directory.Exists(Server.MapPath(path))) 6 { 7 Directory.CreateDirectory(Server.MapPath(path)); 8 } 9 if (file != null) 10 { 11 string filePath = string.Format("{0}/{1}{2}", path, System.Guid.NewGuid(), System.IO.Path.GetExtension(file.FileName)); 12 file.SaveAs(Server.MapPath(filePath)); 13 } 14 return View(); 15 }
2.多个文件上传
就是form表单中多个input file
1 @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 2 { 3 <input type="file" id="file" name="file1" /> 4 <input type="file" id="file" name="file2" /> 5 <input type="file" id="file" name="file3" /> 6 <input type="file" id="file" name="file4" /> 7 <input type="file" id="file" name="file5" /> 8 <input type="file" id="file" name="file6" /> 9 <br/> 10 <input type="submit" value="提交"/> 11 }
1 public class HomeController:Controller 2 { 3 public ActionResult Index() 4 { 5 foreach (string upload in Request.Files) 6 { 7 if (!Request.Files[upload].HasFile()) continue; 8 string path = "/uploadImg/"; 9 string filename = Path.GetFileName(Request.Files[upload].FileName); 10 Request.Files[upload].SaveAs(Path.Combine(path, filename)); 11 } 12 return View(); 13 } 14 }
3.文件下载
HTML中:<a href="/GetFile">下载文件</a>
View中:@Html.ActionLink("下载文件", "Download", "Home");
直接下载到默认下载中
1 public class HomeController : Controller 2 { 3 public FilePathResult GetFileFromDisk() 4 { 5 string path = @"/uploadImg/"; 6 string fileName = "5141fb63-955b-4f0b-9f53-ab770329e6f5.png"; 7 return File(path + fileName, "image/png", fileName); 8 } 9 10 public FileStreamResult StreamFileFromDisk() 11 { 12 string path = AppDomain.CurrentDomain.BaseDirectory + "uploadImg/"; 13 string fileName = "5141fb63-955b-4f0b-9f53-ab770329e6f5.png"; 14 return File(new FileStream(path + fileName, FileMode.Open), "image/png", fileName); 15 } 16 } 17 }

浙公网安备 33010602011771号