Download file of any type in Asp.Net MVC using FileResult?

后端 未结 9 1875
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 05:05

I\'ve had it suggested to me that I should use FileResult to allow users to download files from my Asp.Net MVC application. But the only examples of this I can find always h

9条回答
  •  天涯浪人
    2020-11-22 05:20

    Phil Haack has a nice article where he created a Custom File Download Action Result class. You only need to specify the virtual path of the file and the name to be saved as.

    I used it once and here's my code.

            [AcceptVerbs(HttpVerbs.Get)]
            public ActionResult Download(int fileID)
            {
                Data.LinqToSql.File file = _fileService.GetByID(fileID);
    
                return new DownloadResult { VirtualPath = GetVirtualPath(file.Path),
                                            FileDownloadName = file.Name };
            }
    

    In my example i was storing the physical path of the files so i used this helper method -that i found somewhere i can't remember- to convert it to a virtual path

            private string GetVirtualPath(string physicalPath)
            {
                string rootpath = Server.MapPath("~/");
    
                physicalPath = physicalPath.Replace(rootpath, "");
                physicalPath = physicalPath.Replace("\\", "/");
    
                return "~/" + physicalPath;
            }
    

    Here's the full class as taken from Phill Haack's article

    public class DownloadResult : ActionResult {
    
        public DownloadResult() {}
    
        public DownloadResult(string virtualPath) {
            this.VirtualPath = virtualPath;
        }
    
        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 = context.HttpContext.Server.MapPath(this.VirtualPath);
            context.HttpContext.Response.TransmitFile(filePath);
        }
    }
    

提交回复
热议问题