我正在尝试实现PHP强制下载并使用下面的代码
$length = sprintf("%u", filesize($path));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
readfile($path);
exit;
文件以完整大小成功下载(我在记事本++中打开文件并且没有php错误或警告)但我无法打开文件。奇怪的是我可以下载并打开pdf文件,没有任何问题。但是像docx,png,jpg这样的格式的文件是courrepted
答案 0 :(得分:0)
尝试暂时删除内容长度标题,这可能是错误的并导致文件未完全下载(可能是单个字节)。同时尝试将您的到期时间设置为高于0;我看到IE中的错误是由于浏览器在外部程序有时间加载它之前从缓存中删除文件。
答案 1 :(得分:0)
将此用于强制下载
header("Cache-Control: maxage=1");
header("Pragma: public");
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($path));
header("Content-disposition: attachment; filename=\"".basename($path)."\"");
答案 2 :(得分:0)
我认为您应该使用正确的内容类型
以下是内容类型列表: http://www.freeformatter.com/mime-types-list.html
答案 3 :(得分:0)
试试此代码
$file = "xyz.html"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
readfile($file);
答案 4 :(得分:0)
$file=FCPATH."downloaded/1462026746_IMG_2015.JPG"; //file location
if(file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
else {
die('The provided file path is not valid.');
}
答案 5 :(得分:-1)
在标题之前添加ob_get_clean();
ob_clean(); flush();
之前的readfile();
我有同样的问题,这解决了我。