下载文件,不在浏览器上加载

时间:2013-12-17 10:28:24

标签: jquery download operating-system save

我的网站上有一个按钮,当用户点击时调用jQuery函数

event.preventDefault();
document.location.href = 'www.abcd.com/manual.pdf';

此操作在浏览器窗口中打开'manual.pdf',但我想下载它...如何在当前操作系统上打开'SaveAs'对话框?

2 个答案:

答案 0 :(得分:1)

HTML5 download attribute:

<a href="www.abcd.com/manual.pdf" download>Download File</a>

这将打开save as对话框

答案 1 :(得分:1)

对于本地文件,您可以使用php执行此操作。诀窍是设置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" ...>