代码
/**
* 使用header下载文件
* @access public
* @param file_path 文件路径
* @return null
*/
function downloadFile($file_path){
//判断路径是否存在
if(!file_exists($file_path)){
echo "文件不存在";
return;
}
$fp = fopen ($file_path, "rb"); // 文件以二进制形式打开
$ua = $_SERVER["HTTP_USER_AGENT"];
//取得文件信息
$file_size = filesize($file_path);
$file_name = basename($file_path);
$encoded_file_name = urlencode($file_name);
$encoded_file_name = str_replace("+", "%20", $encoded_file_name);
header('Content-Type: application/octet-stream;charset=utf-8');
header("Accept-Ranges:bytes");
header("Accept-Length:".$file_size);
// 兼容多浏览器下载
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename=' . $encoded_file_name);
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*=utf8\'\'' . $file_name);
} else {
header('Content-Disposition: attachment; filename=' . $file_name);
}
// 清除缓存很重要
ob_clean();
flush();
// 清除缓存很重要
$buffer = 1024;
$buffer_count = 0;
while (!feof($fp) && $file_size - $buffer_count > 0) {
$data = fread($fp, $buffer);
$buffer_count += $buffer;
echo $data;
}
fclose($fp);
exit(); // 一定要使用exit退出,否则会导致输出excel文件无法打开
}