我有一个列出附件的网站。单击这些附件会导致以下两种行为之一 -
- 附件会在同一窗口中打开。
- 附件向用户显示一个用于打开或保存文档的对话框。
第 1 点似乎只发生在 PDF 中,但有没有办法让所有附件向用户显示“保存/打开/取消”弹出窗口?
最佳答案
仅适用于 PDF ..
// The user will receive a PDF to download
header('Content-type: application/pdf');
// File will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The actual PDF file on the server is source.pdf
readfile('source.pdf');
...
对于所有其他文件类型,也许您可以使用 .. echo mime_content_type('Yourfile.ext')
o
header('Content-type: '.mime_content_type('Yourfile.ext'));
header('Content-Disposition: attachment; filename="'.$output_filename.'"');
readfile($source_filename);
请注意,我还没有测试过......
Content-type header 指定要下载的文件类型,由 mime 类型指定。 Content-Disposition header 指定要下载的文件的新文件名。 readfile 行不是发送的 header ,而是从文件中获取所有数据并将其输出的 PHP 调用。您传递给 readfile 函数的参数是要下载的实际 pdf 文件的位置。
更新
mime_content_type()
函数已弃用。你需要用这个替换...
$finfo = new finfo;
$fileinfo = $finfo->file($file, FILEINFO_MIME);
关于php - 强制下载附件而不是自动打开它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12404344/