我在我的网页上提供了一个PDF文件的链接供下载,如下所示
<a href="myfile.pdf">Download Brochure</a>
问题是,当用户点击这个链接时,然后
但我希望它总是弹出让用户下载,而不管是否安装了Adobe Acrobat。
请告诉我如何才能做到这一点?
与其链接到.PDF文件,不如做以下事情
<a href="pdf_server.php?file=pdffilename">Download my eBook</a>
输出一个自定义的标题,打开PDF(二进制安全)并将数据打印到用户的浏览器,然后他们可以选择保存PDF,尽管他们的浏览器设置。 pdf_server.php看起来应该是这样的。
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
PS: 显然,对"file"变量进行一些理智的检查,以防止人们窃取你的文件,如不接受文件扩展名,拒绝斜线,在值中加入.pdf。
在Ruby on Rails应用程序中(特别是使用像Prawn gem和Prawnto Rails插件这样的东西),你可以比完整的脚本(如前面的PHP例子)更简单地完成这个任务。
在你的控制器中。
def index
respond_to do |format|
format.html # Your HTML view
format.pdf { render :layout => false }
end
end
render :layout => false部分告诉浏览器打开"你想下载这个文件吗?"提示,而不是尝试渲染PDF。然后你就可以正常链接到该文件:http://mysite.com/myawesomepdf.pdf