强制浏览器下载PDF文档,而不是打开它
本文关键字:浏览器 下载 PDF 文档 | 更新日期: 2023-09-27 18:18:25
我想让浏览器从服务器下载PDF文档,而不是在浏览器中打开文件。我正在使用c#。
下面是我使用的示例代码。It not working.
string filename = "Sample server url";
response.redirect(filename);
你应该看看"Content-Disposition" header;例如,将"内容处理"设置为"附件;filename=foo.pdf"会提示用户(通常)一个"Save as: foo.pdf"对话框,而不是打开它。但是,这需要来自正在进行下载的请求,因此在重定向期间不能这样做。然而,ASP。NET为此目的提供了Response.TransmitFile
。例如(假设您不使用MVC,它有其他首选选项):
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
如果您想呈现文件,以便您可以将它们保存在您的终端,而不是在浏览器中打开,您可以尝试以下代码片段:
//create new MemoryStream object and add PDF file’s content to outStream.
MemoryStream outStream = new MemoryStream();
//specify the duration of time before a page cached on a browser expires
Response.Expires = 0;
//specify the property to buffer the output page
Response.Buffer = true;
//erase any buffered HTML output
Response.ClearContent();
//add a new HTML header and value to the Response sent to the client
Response.AddHeader(“content-disposition”, “inline; filename=” + “output.pdf”);
//specify the HTTP content type for Response as Pdf
Response.ContentType = “application/pdf”;
//write specified information of current HTTP output to Byte array
Response.BinaryWrite(outStream.ToArray());
//close the output stream
outStream.Close();
//end the processing of the current page to ensure that no other HTML content is sent
Response.End();
然而,如果你想使用客户端应用程序下载文件,那么你就必须使用WebClient类。
我通过将inline参数设置为true,它将在浏览器中显示false,它将在浏览器中显示另存为对话框
public void ExportReport(XtraReport report, string fileName, string fileType, bool inline)
{
MemoryStream stream = new MemoryStream();
Response.Clear();
if (fileType == "xls")
report.ExportToXls(stream);
if (fileType == "pdf")
report.ExportToPdf(stream);
if (fileType == "rtf")
report.ExportToRtf(stream);
if (fileType == "csv")
report.ExportToCsv(stream);
Response.ContentType = "application/" + fileType;
Response.AddHeader("Accept-Header", stream.Length.ToString());
Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.{2}", (inline ? "Inline" : "Attachment"), fileName, fileType));
Response.AddHeader("Content-Length", stream.Length.ToString());
//Response.ContentEncoding = System.Text.Encoding.Default;
Response.BinaryWrite(stream.ToArray());
Response.End();
}
如果我们试图写一个字节数组,那么我们可以使用以下一个。
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.pdf");
Response.BufferOutput = true;
Response.AddHeader("Content-Length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
Response.End();
它们在大多数情况下几乎是相同的,但有一个区别:
Add Header将用相同的键
替换前一个条目Append头不会替换键,而是添加另一个键。