Asp.net mvc3 文件下载的实现

1.控制器的ActionResult

  public ActionResult DownLoadFile()
        {
            string filePath = Server.MapPath("~/ResourceFile/1ef53469-cbac-4007-b40b-ae68644794e7.doc");
            return new DownloadResult(filePath, "1ef53469-cbac-4007-b40b-ae68644794e7.doc");        
        }

2.DownLoadResult类的实现

 public class DownloadResult : ActionResult
    {
        public DownloadResult()
        {
        }

        public DownloadResult(string virtualPath,string fileDownloadName)
        {
            this.VirtualPath = virtualPath;
            this.FileDownloadName = fileDownloadName;
        }

        public string VirtualPath
        {
            get;
            set;
        }

        public string FileDownloadName
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context) {
              if (!String.IsNullOrEmpty(FileDownloadName)) {
                  context.HttpContext.Response.AddHeader("content-disposition",
                    "attachment; filename=" + this.FileDownloadName);
    }

    string filePath = this.VirtualPath;
    context.HttpContext.Response.TransmitFile(filePath);
    }

    }

posted on 2012-04-26 19:05  khh  阅读(671)  评论(1编辑  收藏  举报

导航