PDF强制下载而不是在浏览器中打开

时间:2014-01-10 15:30:31

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razorpdf

我正在使用RazorPDF,我想强制下载PDF而不是在浏览器标签中打开。我该怎么做呢?感谢

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Id)
{
    return RedirectToAction("Pdf");
}

public PdfResult Pdf()
{
    // With no Model and default view name.  Pdf is always the default view name
    return new PdfResult();
}

2 个答案:

答案 0 :(得分:7)

尝试在返回content-disposition对象之前添加PDFResult标头。

public PdfResult Pdf()
{
  Response.AddHeader("content-disposition", "attachment; filename=YourSanitazedFileName.pdf");

  // With no Model and default view name.  Pdf is always the default view name
  return new PdfResult();
}

答案 1 :(得分:0)

你应该看看" Content-Disposition"报头;例如设置" Content-Disposition"到"附件;文件名= FileName.pdf"将提示用户(通常)使用"另存为:FileName.pdf"对话,而不是打开它。但是,这需要来自正在进行下载的请求,因此您无法在重定向期间执行此操作。但是,ASP.NET为此提供了Response.TransmitFile。例如(假设您没有使用MVC,它有其他首选选项):

Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Response.TransmitFile(filePath);
Response.End(); 

如果您尝试在Api中将文件打开转换为BytesArray,然后填写内容

            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            FileStream stream = File.OpenRead(path);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();           
            result.Content = new ByteArrayContent(fileBytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "FileName.pdf";