所以首先我想告诉我,我在使用标头和使用输出缓冲区方面是个新手。所以我正在为 liferay 开发 php portlet,我在文件下载方面遇到了一些问题。我试图简单地使用'a href'来做到这一点,但问题是通过php上传的文件在刷新apache之前不可用,所以我尝试了另一种使用header()函数的方法。
所以我会试着解释我的问题。当我在简单的 php 项目上尝试以下代码时,它工作正常:
<?php
$path = "/mysecretdir/upload/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch($ext) {
case "pdf":
$ctype = "application/pdf";
break;
case "exe":
$ctype = "application/octet-stream";
break;
case "zip":
$ctype = "application/zip";
break;
case "doc":
$ctype = "application/msword";
break;
case "xls":
$ctype = "application/vnd.ms-excel";
break;
case "ppt":
$ctype = "application/vnd.ms-powerpoint";
break;
case "gif":
$ctype = "image/gif";
break;
case "png":
$ctype = "image/png";
break;
case "jpeg":
$ctype = "image/jpg";
break;
case "jpg":
$ctype = "image/jpg";
break;
case "mp3":
$ctype = "audio/mp3";
break;
case "wav":
$ctype = "audio/x-wav";
break;
case "wma":
$ctype = "audio/x-wav";
break;
case "mpeg":
$ctype = "video/mpeg";
break;
case "mpg":
$ctype = "video/mpeg";
break;
case "mpe":
$ctype = "video/mpeg";
break;
case "mov":
$ctype = "video/quicktime";
break;
case "avi":
$ctype = "video/x-msvideo";
break;
case "src":
$ctype = "plain/text";
break;
default:
$ctype = "application/force-download";
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-type: " . $ctype);
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
header("Content-Transfer-Encoding: binary");
//header("Content-length: $fsize");
header("Cache-control: public"); //use this to open files directly
while(!feof($fd)) {
echo fread($fd, 4096);
flush();
}
}
fclose ($fd);
?>
从 index.php 我用 href="download.php?download_file=/something/" 调用它
好的,但现在重点。当我在liferay portlet 中使用它时,文件很奇怪。它将整个生成的 HTML 文件放入创建的文件中。所以它坏了。我不知道为什么。我不知道标头是否从其他地方发送了一些信息,也不知道如何修复它。
我花了几个小时寻找一些解决方案,但不知道如何以某种方式为标题创建“会话”,因为我认为它们有问题。因为没有回声,它只打印文件和其他项目的内容 - 更简单的 php 应用程序不是它的门户的一部分!但也许我错了。
那么请有人可以帮助我吗?有什么建议吗?