我希望用户在点击“下载此文件”链接时下载文件。
用例:用户点击一个链接,网络应用生成一个文件并将其“推送”为下载。
我有以下 PHP 代码。尽管文件在服务器中正确生成,但并未下载(也未显示下载对话框)。
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
readfile('file.zip');
我尝试添加以下内容,但它不起作用:
header("Location: file.zip"); // not working
不过,我通过尝试以下重定向找到了一个 JavaScript 解决方案(有效):
window.location.href = 'file.zip';
问题是,执行上面的 JavaScript 操作会尝试“卸载”当前窗口/表单,在这种情况下这对我不起作用。
是否有仅使用 PHP 来“强制”下载文件(在本例中为“file.zip”)的解决方案?
最佳答案
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
还要确保根据您的文件 application/zip、application/pdf 等添加正确的内容类型 - 但前提是您不想触发另存为对话框。
关于javascript - 如何使用PHP强制下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725375/