我试图使用PHP来强制客户端计算机上下载(文件对话框 - 没有什么险恶)。我发现很多页面推荐使用header()函数来控制我的PHP脚本的响应,但是我对此没有任何好运。我的代码如下:PHP强制文件下载
$file = $_POST['fname'];
if(!($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file)) {
die('File not found.');
} else {
header('Pragma: public');
header('Content-disposition: attachment; filename="tasks.zip"');
header('Content-type: application/force-download');
header('Content-Length: ' . filesize($file));
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
ob_end_clean();
readfile($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file);
}
我使用这个JavaScript调用它:
$.ajax({
url: url,
success: function(text) {
var req = new XMLHttpRequest();
req.open("POST", 'php/utils/getXMLfile.php', true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send('fname=' + encodeURIComponent(text));
}
});
这将返回文件作为文本的内容,但不会触发下载对话框。有没有人有什么建议?而不是使用AJAX的
我不认为它是重复的。这里的问题稍有不同。问题是post操作的结果不会触发由php生成的答案的头部中指定的下载行为。 – ALoopingIcon 2017-02-11 16:37:21