php 如何强制PDF下载初学者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11990902/
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-08-25 02:35:09  来源:igfitidea点击:

How to force PDF to download beginner

phppdfheaderforce-download

提问by Daniel Ramirez-Escudero

Possible Duplicate:
How to force a pdf download automatically?

可能重复:
如何强制自动下载 pdf?

I've checked other forums, but I do not understand what they say. I've checked this link which people do seem to get the solution:

我检查了其他论坛,但我不明白他们在说什么。我检查了这个链接,人们似乎确实得到了解决方案:

http://css-tricks.com/snippets/htaccess/force-files-to-download-not-open-in-browser/

http://css-tricks.com/snippets/htaccess/force-files-to-download-not-open-in-browser/

I want to do a button which is done for downloading a PDF, the file is too big to see it online. So I want that button to force the browser to download the file. Asking or not asking the user. There will be different PDF name files so I need to make this button downloadable with PDF formats of various PDF files.

我想做一个用于下载PDF的按钮,文件太大而无法在线查看。所以我希望该按钮强制浏览器下载文件。询问或不询问用户。会有不同的 PDF 名称文件,所以我需要让这个按钮可以下载各种 PDF 文件的 PDF 格式。

I've checked different webs and it seems it can be done using htaccess, but I honestly have no clue of how to do this. Can somebody help to show me how I can do this!?!?! Is there a simple way via CSS/html??

我检查了不同的网站,似乎可以使用 htaccess 来完成,但老实说我不知道​​如何做到这一点。有人可以帮我看看我怎么能做到这一点!?!?!有没有通过 CSS/html 的简单方法?

I've been stuck for a long while for such a small detail.

我已经被困在这么一个小细节上很长时间了。

My code is simply:

我的代码很简单:

<div class="Container for icons">
<a href="hugefile.pdf" alt=""><img href="icon.png" alt=""/>
</div>

Could somebody give me hand on this one?

有人可以帮我解决这个问题吗?

回答by paulsm4

You'll need to modify the HTTP header returned to the client in order to accomplish this:

您需要修改返回给客户端的 HTTP 标头才能完成此操作:

Here's a PHP code example:

这是一个 PHP 代码示例:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // For download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  //this is necessary in order to get it to actually download the file, otherwise it will be 0Kb

回答by Oriol

Instead of AddTypeyou could try ForceType:

而不是AddType你可以尝试ForceType

<FilesMatch "\.(pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>