【问题标题】:php: force download to hd?php:强制下载到高清?
【发布时间】:2010-07-23 00:38:58
【问题描述】:
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: application/force-download");
header("Content-Disposition: attachment; filename=\"". $file ."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
file_get_contents($file);
readfile($file);
exit();

知道我做错了什么吗?这不应该将任何文件从我的服务器下载到用户的硬盘吗?不知何故,每个文件都损坏了!此外,我想知道如何更改下载文件的文件名?

$file 始终包含我的文件的完整路径。 如果我尝试header('Location:' . $file );,浏览器会成功打开我的文件。但是,如果文件是 .jpg,则浏览器不会提示下载窗口。相反,它只是在浏览器窗口中打开文件。我希望每个文件都下载到高清。

请帮帮我。我已经为此苦苦挣扎了一个多星期,但找不到解决方案?

【问题讨论】:

  • 如果 $file 包含一个路径,而不仅仅是您应该使用的名称 filename=\"". basename($file) ."\";" 以及 file_get_contents($file); 行应该做什么?

标签: php download


【解决方案1】:

为什么不使用

header("Content-type: application/octet-stream");

而不是“强制下载”

还有你为什么要做file_get_contentsreadfile?只需要一个 - 您基本上包含两次文件,这就是它损坏的原因。以下是我将如何执行上述代码:

header("Cache-Control: no-cache");
header("Expires: -1");
header("Content-Type: application/octet-stream;");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file));
echo file_get_contents($file);

这就足够了——只要文件确实存在

【讨论】:

  • 我更喜欢readfile($file) 而不是echo file_get_contents($file)。无需将整个文件内容读入内存(作为字符串)然后回显。
  • 这是真的。该脚本的主要问题是缺少内容处置的基本名称以及包含两个“文件读取”功能。 readfile 可能更适合 - 我一直使用 file_get_contents
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 2012-07-17
相关资源
最近更新 更多