Html中的代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <meta charset="utf-8" /> 7 <script src="Contents/JScript/jquery.min.js"></script> 8 </head> 9 <body> 10 <form id="uploadForm"> 11 <!-- ajax请求的话不需要method="post" action="MvcUload.html" enctype="multipart/form-data"这些参数,否则405错误--> 12 <!--<form method="post" action="MvcUload.html" enctype="multipart/form-data" id="uploadForm">--> 13 <input type="file" name="file" id="file" /><button onclick="fnUpload()">上传文件</button> 14 </form> 15 <form method="post" action="../../UploadFiles/DownLoadFile" enctype="multipart/form-data" id="uploadForm1"> 16 <button onclick="fnSubmit()">下载文件</button> 17 </form> 18 <script> 19 function fnUpload() { 20 var formData = new FormData($("#uploadForm")[0]);//var formData = new FormData();//formData.append("file", $("#file")[0].files[0]); //获取文件法二 两种方法都可以
21 $.ajax({ 22 async: false,//要求同步 不是不需看你的需求 23 url: "../UploadFiles/SaveFile", 24 type: 'POST', 25 data: formData, 26 processData: false, //必须false才会避开jQuery对 formdata 的默认处理 27 contentType: false, //必须false才会自动加上正确的Content-Type 28 success: function (res) { 29 alert(res); 30 }, error: function (res) { 31 alert("请求失败"); 32 } 33 }); 34 35 } 36 function fnSubmit() { 37 $("#uploadForm1").submit(); 38 } 39 </script> 40 </body> 41 </html>
C#后台控制器里面的方法:
1 public class UploadFilesController : Controller 2 { 3 //保存文件 4 public string SaveFile() 5 { 6 var result = ""; 7 HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; 8 if (files.Count>0) 9 { 10 HttpPostedFile file = files[0];//一次上传一个文件 11 if (file.ContentLength > 0) 12 { 13 try 14 { 15 var path = Server.MapPath("../uploadfiles"); 16 if (!Directory.Exists(path)) Directory.CreateDirectory(path); 17 var combineName = System.IO.Path.Combine(path, System.IO.Path.GetFileName(file.FileName));//组合成路径 18 file.SaveAs(combineName); 19 result = "文件上传成功!"; 20 } 21 catch (Exception e) 22 { 23 result = e.ToString(); 24 } 25 } 26 else 27 result = "文件不能为空!"; 28 } 29 else 30 result = "文件不能为空!"; 31 return result; 32 } 33 34 //下载文件 35 public void DownLoadFile() 36 { 37 HttpRequest request = System.Web.HttpContext.Current.Request; 38 var re = request.Url;//查看请求地址,发现 /UploadFiles/DownLoadFile request.Url.LocalPath http://localhost:2565/UploadFiles/DownLoadFile request.Url.OriginalString 39 //请求地址都不是Controllers文件夹下面的地址,需要注意表单action的地址 40 HttpResponse response = System.Web.HttpContext.Current.Response; 41 var files = Directory.GetFiles(Server.MapPath("../uploadfiles")); 42 if (files.Length > 0) { 43 var fileUrl = files[0];//取第一个下载 44 var fileArr = fileUrl.Split('\'); 45 var fileName = fileArr[fileArr.Length - 1]; 46 response.Clear(); 47 response.ContentType = "application/octet-stream"; 48 response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName)); 49 response.TransmitFile(fileName); 50 } 51 } 52 }