首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >强制浏览器下载PDF文档而不是打开它

强制浏览器下载PDF文档而不是打开它
EN

Stack Overflow用户
提问于 2011-12-21 21:26:04
回答 4查看 67.4K关注 0票数 23

我想让浏览器从服务器下载PDF文档,而不是在浏览器中打开文件。我正在使用C#。

下面是我使用的示例代码。它不工作了..

代码语言:javascript
复制
string filename = "Sample server url";
response.redirect(filename);
EN

回答 4

Stack Overflow用户

发布于 2011-12-21 21:40:27

如果您希望呈现文件,以便可以在您的端保存它们,而不是在浏览器中打开它们,您可以尝试以下代码片段:

代码语言:javascript
复制
//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 class

票数 4
EN

Stack Overflow用户

发布于 2015-04-07 13:38:26

我通过将inline参数设置为true来使用它,它将在浏览器中显示false,它将在浏览器中显示另存为对话框。

代码语言:javascript
复制
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();
}
票数 3
EN

Stack Overflow用户

发布于 2020-01-22 20:18:59

如果我们试图写一个字节数组,那么我们可以使用下面的数组。

代码语言:javascript
复制
            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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8590543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档