PHP强制文件下载
我试图使用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的
,只是将浏览器重定向到相关网址。当它收到content-disposition:attachment
标题时,它将下载该文件。
如果我重定向浏览器,它不会清除已加载的页面吗?这有些问题,因为这只是一个更大的页面的一小部分。 – Crash 2012-08-06 21:52:38
+1非常真实,如果您不需要调用的结果,为什么要使用AJAX? – 2012-08-06 21:52:45
@Crash它不会重定向,只是“保存文件”对话框将弹出... – 2012-08-06 21:54:34
几点建议:
1.
if(!($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file)) {
相反:
if(!file_exists($baseDir ....)){
2.不要需要的尺寸。
3.Try这一个:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fullpath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($fullpath);
exit;
我会尝试从PHP发送一个头这样的,以取代您application/force-download
头:
header("Content-type: application/octet-stream");
我试过那个 – Crash 2012-08-06 22:05:36
Kolink的回答为我工作(改变窗口位置的PHP文件),但因为我想发送POST变量与请求一起,我最终使用了一个隐藏的窗体。我使用的代码如下:
var url = 'php/utils/getXMLfile.php';
var form = $('<form action="' + url + '" method="post" style="display: none;">' +
'<input type="text" name="fname" value="' + text + '" />' +
'</form>');
$('body').append(form);
$(form).submit();
感谢您的所有答案!
我不认为它是重复的。这里的问题稍有不同。问题是post操作的结果不会触发由php生成的答案的头部中指定的下载行为。 – ALoopingIcon 2017-02-11 16:37:21