【问题标题】:How to allow user to download file to own harddrive - MVC如何允许用户下载文件到自己的硬盘 - MVC
【发布时间】:2011-10-11 20:06:39
【问题描述】:

我的 MVC Web 应用程序中的一个视图具有允许用户查看存储在服务器计算机上的特定文本文件的 URL。这是相关的控制器函数(假设路径已经定义):

 Public Function DownloadResults() As ActionResult
        Return File(path, "text/plain")
 End Function

上面的内容在视图中被一些简单的东西调用,即<%=Html.ActionLink("View File", "DownloadResults")%>。当用户点击查看文件 URL 时,他们会被重定向到一个 URL,在该 URL 中文本文件的内容会打印在浏览器的页面上。

但是,我想做的是弹出一个对话框,询问用户是否要下载文件,并在确认后将 .txt 的物理副本下载到他们的下载文件夹中。实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: asp.net-mvc download


    【解决方案1】:

    您需要在响应标头中设置附件。为此,您可以创建 ActionResult,例如:

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

    菲尔·哈克:http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2018-04-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多