【发布时间】:2010-08-25 07:37:46
【问题描述】:
最终目标是让用户下载 .csv 文件。现在我只是在测试尝试下载一个简单的文本文件:test.txt。该文件中唯一的内容是“test”一词。
这是 files_to_download.php 的 HTML 代码
Test file: <a href='test.php?file=test.txt'>Test.txt</a>
test.php 的代码:
if(!(empty($_GET["file"])))
{
$file_name = $_GET["file"];
$path = "path/to/file";
$fullPath = $path . $file_name;
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: inline; attachment; filename=\"$file_name\"");
header("Content-Type: text/plain");
header("Content-Transfer-Encoding: binary");
readfile($fullPath);
}
我尝试了上述标题的变体,添加了更多并删除了其他标题。以上似乎是本网站上最常见的推荐。
我也尝试过改变
header("Content-Type: text/plain");
到
header("Content-Type: text/csv");
并获得相同的结果:空 .txt 或 .csv 文件。
当我从服务器直接打开它们(文件浏览器)时,文件不是空的。我检查了文件的权限,它们都是644,所以至少全世界都可以读取这些文件。目录是 777。
Apache 服务器上是否有我需要指定的配置可能没有或我缺少上面的某些内容。
感谢收看!
【问题讨论】:
-
您应该检查
$fullPath并确保它是您想要的路径。在您的示例中,$fullPath是"path/to/filetest.txt"而不是"path/to/file/test.txt"。 -
如果您将
readfile($fullPath);替换为echo 'foo',代码对我来说可以正常工作,所以我投票支持路径问题。