【发布时间】: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