代码之家  ›  专栏  ›  技术社区  ›  Gautam Jain

如何链接到ASP.NET MVC中的可下载文件?

  •  4
  • Gautam Jain  · 技术社区  · 16 年前

    我是ASP.NET MVC的新手,我正在尝试链接到可下载的文件(.zip,.mp3,.doc等)。
    我有以下观点: ProductName 映射到: http://domain/ProductName
    我有一个 .zip 必须映射到URL的文件 http://domain/ProductName/Product.zip

    问题

    我把这个放哪 邮编 文件在MVC文件夹结构中?
    我该怎么添加这个链接呢 邮编 MVC中的文件?有URL.*方法吗?

    3 回复  |  直到 9 年前
        1
  •  18
  •   takepara    16 年前

    您可以使用filePathResult或controller.file方法。

    protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName) {
      return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };
    }
    

    示例代码操作方法。

    public ActionResult Download(){
      return File(fileName,contentType,downloadFileName);
    }
    

    希望这个代码。

        2
  •  8
  •   Stacked Emily M    10 年前

    下面的类添加了一个文件 DownloadResult 到您的程序:

    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);
        }
    }
    

    要调用它,请在控制器方法中执行如下操作:

    public ActionResult Download(string name)
    {
        return new DownloadResult 
           { VirtualPath = "~/files/" + name, FileDownloadName = name };
    }
    

    请注意虚拟路径,它是站点根目录中的文件目录;可以将其更改为所需的任何文件夹。这是你下载文件的地方。 查看本教程关于 Writing A Custom File Download Action Result For ASP.NET MVC

        3
  •  0
  •   ScottLenart    9 年前

    另一个使用fileresult的简化示例如takepara所示。

    注意,我创建了一个helpercontroller.cs类。

    在你看来…

    @Html.ActionLink("Link Description", "Download", "Helper", new { fileName = "downloaded_file_name.ext", path = "root path location to your file" }, null)
    


    控制器操作…

    public FileResult Download(string fileName, string path)
    {
        var webRootPath = Server.MapPath("~");
        var documentationPath = Path.GetFullPath(Path.Combine(webRootPath, path));
        var filePath = Path.GetFullPath(Path.Combine(documentationPath, fileName));
    
        return File(filePath, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }