View:
1 <div> 2 <input id="btn1" type="button" value="Redirect" onclick="fun1()" /> 3 <hr /> 4 <input id="btn2" type="file"> 5 <input id="upload" type="button" value="单个上传" onclick="Upload()" /> 6 <hr /> 7 <input id="btn3" name="btn3" type="file" multiple="multiple"> 8 <input id="uploads" type="button" value="多个上传" onclick="Uploads()" /> 9 </div> 10 11 @section scripts{ 12 <script type="text/javascript"> 13 $(function () { 14 }); 15 //批量文件上传 16 function Uploads() { 17 var files = $("#btn3")[0].files; 18 var formData = new FormData(); 19 for (var i = 0; i < files.length; i++) { 20 // var name = files[i].name; 21 var file = files[i]; 22 23 formData.append("file" + i, file); 24 // formData.append("name" + i, name); 25 } 26 27 28 $.ajax({ 29 url: "/Home/UploadFiles", 30 type: "POST", 31 processData: false, 32 contentType: false, 33 data: formData, 34 success: function (data) { 35 alert(data); 36 } 37 }) 38 }; 39 function fun1() { 40 window.open("/Home/M1", "_black"); 41 }; 42 //单个文件上传 43 function Upload() { 44 var data = $("#btn2")[0].files[0]; 45 var fd = new FormData(); 46 fd.append("file", data); 47 $.ajax({ 48 url: "/Home/UploadFile1", 49 type: "POST", 50 processData: false, 51 contentType: false, 52 data: fd, 53 success: function (data) { 54 alert(data); 55 } 56 }) 57 }; 58 </script> 59 }
Controller:
1 public ActionResult UploadFiles() 2 { 3 HttpFileCollectionBase files = Request.Files; 4 for(int i=0;i<files.AllKeys.Length;i++) 5 { 6 var fileName = files[i].FileName; 7 using (Stream ms = files[i].InputStream) 8 { 9 if (!System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "UploadFiles")) 10 { 11 // DirectorySecurity securityRules = new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory,AccessControlSections.All); 12 System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "UploadFiles"); 13 } 14 byte[] buffer = new byte[ms.Length]; 15 ms.Read(buffer, 0, (int)ms.Length); 16 System.IO.File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "UploadFiles\\" + fileName, buffer); 17 } 18 } 19 20 return Content("上传成功"); 21 } 22 23 public ActionResult UploadFile1() 24 { 25 var fileName = Request.Files["file"].FileName; 26 using (Stream ms = Request.Files["file"].InputStream) 27 { 28 if (!System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "UploadFiles")) 29 { 30 // DirectorySecurity securityRules = new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory,AccessControlSections.All); 31 System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory+"UploadFiles"); 32 } 33 byte[] buffer = new byte[ms.Length]; 34 ms.Read(buffer, 0, (int)ms.Length); 35 System.IO.File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "UploadFiles\\" + fileName, buffer); 36 } 37 38 39 return Content("上传成功"); 40 }
原文:https://www.cnblogs.com/zoumm/p/12430868.html