ASP.NET MVC 下载文件
一、后端代码
引用:using System.Web.Mvc;
path 可以是相对路径,也可以是绝对路径
1 using System.Web.Mvc; 2 3 public FilePathResult DownloadFile(string path) 4 { 5 6 path = path.Replace("\\", "/"); 7 string type = string.Empty; 8 int extIndex = path.LastIndexOf("."); 9 if (extIndex > 0) 10 { 11 type = "application/" + path.Substring(extIndex + 1); 12 } 13 14 string name = string.Empty; 15 int nameIndex = path.LastIndexOf("/"); 16 if (nameIndex > 0) 17 { 18 name = path.Substring(nameIndex + 1); 19 } 20 21 return File("~/" + path, "application/" + type, name); 22 }
二、前端js
引用了jquery.fileDownload.js插件。
下载地址:https://www.bootcdn.cn/jquery.fileDownload/
1 //文件下载 2 function downloadFileJQuery(filePath) { 3 $.fileDownload('/DocManager/DownloadFile?path=' + filePath); 4 }