【问题标题】:Return FilePathResult Between Views在视图之间返回 FilePathResult
【发布时间】:2014-08-30 00:49:12
【问题描述】:

通常,在 ASP.NET、MVC 或其他方式中,我们通过让用户单击链接/按钮来使客户端下载文件;我假设此链接/按钮操作转到正确的控制器,然后重定向回主页。但是,如何在一系列重定向期间从某个中间控制器进行下载?

基本上,当用户单击按钮创建 PDF 时,操作会转到 PdfController 以创建 PDF,然后,因为我假设他/她无论如何都想下载 PDF(如果他/她不,他/她可以随时单击“否”),我想让浏览器在页面再次呈现之前下载 PDF。如果我还没有失去你,我该如何做到这一点?

这是我目前所拥有的样本。开始动作的按钮:

<a class="btn btn-primary col-md-2 col-md-offset-1" href="@Url.Action("MakePdf", "Pdf")">Create PDF</a>

PdfController 的 MakePdf() 方法:

    public ActionResult MakePdf()
    {
        string PdfUrl = Environment.GetEnvironmentVariable("HOMEDRIVE") + Environment.GetEnvironmentVariable("HOMEPATH") + "/Sites/Bems/PDF/UserPdfs/report" + Id + ".pdf";
        // create the PDF at this PdfUrl

        return RedirectToAction("ShowPdf", "Pdf", new { PdfUrl = PdfUrl });
    }

PdfController 的 ShowPdf() 方法,从之前的 MakePdf() 方法重定向而来:

public ActionResult ShowPdf(string PdfUrl)
    {

        if (System.IO.File.Exists(PdfUrl))
        {
            return File(PdfUrl, "application/pdf"); // Here is where I want to cause the download, but this isn't working
        }
        else
        {
            using (StreamWriter sw = System.IO.File.CreateText(PdfUrl))
            {
                sw.WriteLine("A PDF file should be here, but we could not find it.");
            }
        }

        return RedirectToAction("Edit", "Editor"); // Goes back to the editing page
    }

我试图在我指定的代码中的位置引起下载,但我不确定如何引起它。通常你会以某种方式将它返回到视图中,而我认为在这里我正在调用一个对象,但我对这一切是如何工作的真的很模糊。无论如何,我正在做的事情不起作用。关于那是什么的任何想法?

【问题讨论】:

标签: asp.net asp.net-mvc download


【解决方案1】:

您不能返回 ViewResult RedirectToAction("Edit", "Editor") 并在同一响应中返回 FileResult File(PdfUrl, "application/pdf")

要完成您的任务,您可以遵循以下方案:

  • 点击按钮创建pdf
  • 拨打RedirectToAction("Edit", "Editor");
  • 在这种情况下,在视图的末尾,添加对返回 FileResult 的操作方法的 javascript 调用
  • 一旦页面被渲染,下载将自动开始

【讨论】:

  • 谢谢,这就是我要做的。我希望我可以在 ASP 中完成这一切,但是哦。
猜你喜欢
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多