[英]PDF force download as opposed to open in browser
I am using RazorPDF and I would like to force download the PDF as opposed to open in browser tab. 我正在使用RazorPDF,我想强制下载PDF而不是在浏览器选项卡中打开。 How do I do this?
我该怎么做呢? Thanks
谢谢
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();
}
Try adding the content-disposition
header before returning the PDFResult
object. 尝试在返回
PDFResult
对象之前添加content-disposition
标头。
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();
}
You should look at the "Content-Disposition" header; 您应该查看“Content-Disposition”标题; for example setting "Content-Disposition" to "attachment; filename=FileName.pdf" will prompt the user (typically) with a "Save as: FileName.pdf" dialog, rather than opening it.
例如,将“Content-Disposition”设置为“attachment; filename = FileName.pdf”将提示用户(通常)使用“另存为:FileName.pdf”对话框,而不是打开它。 This, however, needs to come from the request that is doing the download, so you can't do this during a redirect.
但是,这需要来自正在进行下载的请求,因此在重定向期间无法执行此操作。 However, ASP.NET offers Response.TransmitFile for this purpose.
但是,ASP.NET为此提供了Response.TransmitFile。 For example (assuming you aren't using MVC, which has other preferred options):
例如(假设您没有使用MVC,它有其他首选选项):
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Response.TransmitFile(filePath);
Response.End();
If You Are try to open then the file in Api Convert Stream to BytesArray and then Fill the content 如果您尝试打开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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.