Mvc 文件下载
//a 链接方式下载
<a target="_blank" href="/DownLoad/Load">下载</span>
//Js方式下载
function toload() { window.open("DownLoad/Load"); }
//Action内部方法
public FilePathResult Load(string filePath) {
string fileName = ba.adviceAttachment.Substring(1, ba.adviceAttachment.Length - 1);
string FilePath = Path.Combine(Server.MapPath("~/"), fileName.Replace(@"/", "\\"));
string[] files = ba.adviceAttachment.StringSplit("@@");
string fileName1 = files[1];
HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.Charset = "UTF-8"; //指定编码
response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + HttpUtility.UrlEncode(fileName1))); //防止中文乱码
return File(FilePath, "application/octet-stream", fileName1); //正式
return File("F:/UpLoad/Tmp/Wildlife.wmv", "application/octet-stream", "Wildlife.wmv"); //解释上边一句 }
//----------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------
2015-05-12 22:04 补充内容
//action
public FileStreamResult ToDownLoad(int Id) { string virtulPath = "~/UpLoad/BusinessAdvice/潘超.txt"; string physicsPath = Server.MapPath(virtulPath); FileStream fs = new FileStream(physicsPath, FileMode.Open); return File(fs, "text/plain", "潘超.txt"); }
//页面上下载方法
//注意事项:url 和 window.location 地址要保存一致
//经验证,这种方式会访问两次action
function toLoad() { $.ajax({ type:'post', url: "Home/ToDownLoad?Id=1", success:function() { window.location = "Home/ToDownLoad?Id=1"; } }); }
网上找到的,比较容易理解:

浙公网安备 33010602011771号