0

我有一个锚标签:

<a href="file.pdf">Download Me</a>

我希望用户单击它,然后出现一个“另存为”对话框,其中包含我确定的新文件名。

我发现了这个(http://www.w3schools.com/php/func_http_header.asp):

header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
                                
// The PDF source is in file.pdf
readfile("file.pdf");

我不明白把这些标题放在哪里。在页面顶部?当我尝试将这 3 行直接放在链接上方时,我收到以下错误:

警告:无法修改标头信息 - 第 118 行 /home5/ideapale/public_html/amatorders_basic/admin/download.php 中的标头(输出开始于 /home5/ideapale/public_html/amatorders_basic/admin/download.php:38)

我刚刚添加的两个标题行都出现了相同的错误。紧接着,就有数千行 ASCII 字母。如何使用 jQuery 或 PHP(更简单的方法)显示“另存为”对话框?

4

3 回答 3

4

使用 Stijn Van Bael 的代码时请小心,它会让您面临一些严重的安全漏洞。

尝试类似:

--- download.php ---
$allowed_files = array('file.pdf', 'otherfile.pdf');

if (isset($_REQUEST['file']) && in_array($_REQUEST['file'], $allowed_files))
{
  $filename = $_REQUEST['file'];

  header("Content-type:application/pdf");
  header("Content-Disposition:attachment;filename='$filename'");

  // The PDF source is in file.pdf
  readfile($filename);

  exit();
}
else
{
  // error
}


--- linkpage.php ---
<a href="download.php?file=file.pdf">Download PDF</a>
<a href="download.php?file=otherfile.pdf">Download PDF</a>

可能更好的方法是在 Web 服务器级别(这可以在 .htaccess 中)这将强制所有 PDF 被视为二进制文件(强制浏览器下载它们)在您放入的目录中和下面.

<FilesMatch "\.(?i:pdf)$">
 Header set Content-Disposition attachment
 ForceType application/octet-stream
</FilesMatch>
于 2010-07-09T12:57:46.390 回答
0

使用标题和读取文件创建一个新页面,然后使下载链接指向该页面,这将返回 PDF 文件。

例如:

<a href="download.php?file=file.pdf">Download Me</a>

下载.php的来源:

$filename = $_REQUEST['file'];
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='$filename'");

// The PDF source is in file.pdf
readfile($filename);
于 2010-07-09T11:16:15.420 回答
0

或者您可以download在 html 的锚标记中使用新的 HTML5 属性。

代码看起来像

<a download href="path/to/the/download/file"> Clicking on this link will force download the file</a>
于 2013-08-21T05:48:49.387 回答