javascript - 如何使用PHP强制下载文件?

标签 javascript php

我希望用户在点击“下载此文件”链接时下载文件。

用例:用户点击一个链接,网络应用生成一个文件并将其“推送”为下载。

我有以下 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/

相关文章:

php - 添加从 $ 到 $.php 的重写后 nginx CSS 中断

javascript - Jquery Slider UI 动态步长

javascript - 在 SWF 上放置图像

javascript - 按类名从表中删除行

JavaScript/JQuery Div延时函数

php - Zend2 fatal error : Class 'Album\ResultSet' not found

php - Magento:是否可以获得信用卡处理 AVS 和 CSC?

PHP 到 PDF 分页

javascript - 输入字段中的默认文本

Javascript:将十六进制编码的字符串转换为十六进制字节