namespace WebApplication1.Models { public class APIFileHelp { public string[] ExtentsfileName = new string[] { ".doc",".txt", ".xls", ".png", ".jpg" }; public string UrlPath = "/Upload/"; /// <summary> ///响应对象 ,使用前先赋值 /// </summary> public HttpResponse Response = HttpContext.Current.Response; public HttpRequest Request = HttpContext.Current.Request; public string zhi { get; set; } public string UpLoad() { if (Request.Files.Count > 0) { var file = Request.Files[0]; var extenfilename = Path.GetExtension(file.FileName); //判断 路径是否存在 string path = HttpContext.Current.Server.MapPath(UrlPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (ExtentsfileName.Contains(extenfilename.ToLower())) { string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename; string filepath = HttpContext.Current.Server.MapPath(urlfile); file.SaveAs(filepath); return zhi=urlfile; } else { return zhi = "上传失败"; } } else { return zhi = "上传失败"; } } } }
<input type="file" id="f1" /> <input type="button" value="上传文件" onclick="ff()" /> <a href="~/Default/download">下载文件</a> <a href="~/Default/GetFileFromDisk">Click to get file</a> <script> function ff() { var formData = new FormData(); var file = document.getElementById("f1").files[0]; formData.append("fileInfo", file); $.ajax({ url: "/Default/UpLoad/", type: "POST", data: formData, contentType: false,//必须false才会自动加上正确的Content-Type processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理 success: function (data) { //if (data.Code < 0) alert(data) //else }, error: function (data) { alert("上传失败!"); } }); } </script>
namespace WebApplication1.Controllers { public class DefaultController : Controller { APIFileHelp help = new APIFileHelp(); // GET: Default public ActionResult Index() { return View(); } [HttpPost] public string UpLoad() { return help.UpLoad(); } public FilePathResult GetFileFromDisk() { string path = AppDomain.CurrentDomain.BaseDirectory + "Upload/"; string fileName = "新建文本文档.txt"; return File(path + fileName, "text/plain", "test.txt"); } } }