如何强制文件在浏览器中打开而不是下载 (PDF)?

如何强制文件在浏览器中打开而不是下载 (PDF)?

问题描述:

如果未选中在浏览器中显示 PDF"选项,是否可以强制在浏览器中打开 PDF 文件?

Is there a way to force PDF files to open in the browser when the option "Display PDF in browser" is unchecked?

我尝试使用 embed 标记和 iframe,但它仅在选中该选项时才有效.

I tried using the embed tag and an iframe, but it only works when that option is checked.

我能做什么?

要向浏览器指示应该在浏览器中查看文件,HTTP 响应 应包含以下标头:

To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

下载文件而不是查看文件:

Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"

如果文件名包含特殊字符(例如 filename[1].pdf),则文件名周围的引号是必需的,否则可能会破坏浏览器处理响应的能力.

The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.

您如何设置 HTTP 响应标头将取决于您的 HTTP 服务器(或者,如果您从服务器端代码生成 PDF 响应:您的服务器端编程语言).

How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).