【问题标题】:Download file, not load on browser下载文件,不在浏览器上加载
【发布时间】:2013-12-17 10:28:24
【问题描述】:
我的网站上有一个按钮,当用户点击时调用 jQuery 函数
event.preventDefault();
document.location.href = 'www.abcd.com/manual.pdf';
此操作在浏览器窗口中打开“manual.pdf”,但我想下载它...如何在当前操作系统上打开“另存为”对话框?
【问题讨论】:
标签:
jquery
download
operating-system
save
【解决方案2】:
对于本地文件,您可以使用 php.ini 执行此操作。诀窍是设置 HTTP 响应的 Content-Type 和 -Disposition。此 php 脚本将下载限制为 pdf 文件。
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
} else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
另存为download.php并设置<a href="download.php?file=manual.pdf" ...>。