提交表单时自动“下载”PDF

Automatic "download" PDF as upon form submission

本文关键字:下载 PDF 表单 提交      更新时间:2023-09-26

我有一个表单按钮,单击它时它会提交表单。

我希望同时浏览器开始下载PDF文件。我想知道我该怎么做?请记住,默认情况下,PDF通常由浏览器打开,但我希望浏览器"另存为"文件而不打开文件。这只能使用 html 还是我需要 JavaScript?

如果你在服务器端使用PHP,试试这个。这是在我的一个网站中运行的测试代码。

<?php
    ob_start();
    $file = 'YOUR-FILENAME-HERE.pdf';
    if (file_exists($file)) 
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit();
    }
?>

浏览器将提示下载而不显示在浏览器中。

您可以使用此插件通过javascript下载文件。
否则,在javascript中,你可以为它编写代码。

$('a').click(function(e) {
   e.preventDefault();  //stop the browser from following
   window.location.href = 'downloads/file.pdf';
});
<a href="no-script.html">Download now!</a>

或者,您可以使用这个.

在 PHP 中:

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

在 Javascript 中:

<body>
<script>
 function downloadme(x){
    winObj = window.open(x,'','left=10000,screenX=10000');
    winObj.document.execCommand('SaveAs','null','download.pdf');
    winObj.close();
 }
 </script>
 <a href=javascript:downloadme('file.pdf');>Download this pdf</a>
 </body>

在这种情况下,您必须将网络服务器配置为强制下载PDF。如果你使用的是 Apache,不妨看看这篇文章 ->http://www.thingy-ma-jig.co.uk/comment/7264

或者,如果您不必支持所有浏览器,则可以仅使用 html5 下载属性 -> http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

选项 1:您可以让表单提交到的 URL 返回下载。

选项 2:使用 ajax 调用在单击时提交数据,将 window.location 设置为您的下载 URL。

无论 pdf 是在浏览器中打开还是下载,都是您无法控制的客户端设置。