用例:用户单击一个链接,然后Web应用程序生成一个文件并将其“推送”为下载文件.
我有以下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等添加适当的内容类型-但仅当您不希望触发另存为对话框时.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。