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

我希望用户单击“下载此文件链接时下载文件.

用例:用户单击一个链接,然后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等添加适当的内容类型-但仅当您不希望触发另存为对话框时.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...