3
/*
这里的 Virtualpath 表示你要设置下载的文件是哪个?
4
项目中 系统总是默认在UI层的DownLoadFile文件夹中找CITY信息.xls。
5
然后设置FileDownloadName 为你要下载时保存的文件名字是什么,
6
我这里设置的为下载时默认保存为DownFileName.rar
*/
7
return
new
DownloadResult { VirtualPath =
"
~/DownLoadFile/CITY信息.xls
"
, FileDownloadName =
"
城市信息.xls
"
};
2.再接着下面写方法
1 public class DownloadResult : ActionResult
3 public DownloadResult()
7 public DownloadResult(string virtualPath)
9 this.VirtualPath = virtualPath;
10 }
12 public string VirtualPath
13 {
14 get;
15 set;
16 }
18 public string FileDownloadName
19 {
20 get;
21 set;
22 }
23 /*
24 该类主要是对 VirtualPath和FileDownloadName进行初始一下,
25 很重要的一点是AddHeader("content-disposition","attachment; filename="+ this.FileDownloadName);
26 this.FileDownloadName 是在action里new DownloadResult类时,
27 传进来的参数, 下面的Server.MapPath是保存下载文件在什么地方,根据用户选择而定。
28 */
29 public override void ExecuteResult(ControllerContext context)
30 {
31 if (!String.IsNullOrEmpty(FileDownloadName))
32 {
33 context.HttpContext.Response.AddHeader("content-disposition",
34 "attachment; filename=" + this.FileDownloadName);
35 }
37 string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
38 context.HttpContext.Response.TransmitFile(filePath);
39 }
3.View层代码
1 <a href=@Url.Content("/City/DownLoad") iconcls="icon-save">下载</a>
4.完成 用户在指定地址下载文件文件保持的地方用户自己选