apache 提示用户下载 PDF 文件而不是打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1804446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 18:26:34  来源:igfitidea点击:

Prompt user to download PDF file instead of opening

phpjavascriptapache

提问by Jitendra Vyas

In my project site, if I click on a link, the PDF opens in a new or parent window. Well I want a box to appear that prompts the user to download the file instead of opening it.

在我的项目站点中,如果我单击链接,PDF 将在新窗口或父窗口中打开。好吧,我希望出现一个框,提示用户下载文件而不是打开它。

Does anyone know of a simple JavaScript onClick event that will do this, in all browsers, with default settings?

有谁知道一个简单的 JavaScript onClick 事件可以在所有浏览器中使用默认设置执行此操作?

My server is PHP based.

我的服务器是基于 PHP 的。

回答by dxh

Since your edit states that you're using PHP, here's how to do the same in PHP:

由于您的编辑声明您正在使用 PHP,因此在 PHP 中执行相同操作的方法如下:

<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>

回答by dxh

Since you've tagged it .NET, I'd say this is your best solution:

由于您已将其标记为 .NET,因此我认为这是您最好的解决方案:

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf");
Response.WriteFile(Server.MapPath("~/files/myFile.pdf"));
Response.Flush();
Response.Close();

回答by cjk

Change the Content-Type to application/octet-stream. You may find however, that some browsers will infer from the file extension that it should open as a PDF with your favorite PDF viewer.

将 Content-Type 更改为 application/octet-stream。但是,您可能会发现,某些浏览器会根据文件扩展名推断它应该使用您最喜欢的 PDF 查看器以 PDF 格式打开。

Response.ContentType = "application/octet-stream";

Also, set the following:

此外,设置以下内容:

Response.AppendHeader( "content-disposition", "attachment; filename=" + name );

回答by o.k.w

You can't do it via javascript, you need server side implementation.

你不能通过 javascript 来做,你需要服务器端实现。

Here's the SO Post which should help:
Allowing user to download from my site through Response.WriteFile()

这是应该有帮助的 SO Post:
允许用户通过 Response.WriteFile() 从我的站点下载

回答by Miguel

If you are getting a corrupted file error try this:

如果您收到损坏的文件错误,请尝试以下操作:

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/pdf');
header('Content-disposition: attachment; filename=' . basename($file));
header("Content-Transfer-Encoding:  binary");
header('Content-Length: ' . filesize($file)); // provide file size
header('Connection: close');
readfile($file);

Where $fileis the full path or urlof the file.

文件$file的完整路径或 url在哪里。