下载文件之Header方式下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param string $filePath 文件下载
*
* @throws \Exception
*/
public function fileDownload($filePath)
{
if (file_exists($filePath) == false) {
throw new \Exception('文件不存在');
}

$filename = basename($filePath); //获取文件名
header("Content-type: application/octet-stream"); //告诉浏览器这是一个文件流

//处理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = rawurlencode($filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else {
if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
}
readfile($filePath);//将缓冲区的数据写入表格
//让Xsendfile发送文件
/// header("X-Sendfile: $filePath");
}

header头参数详解:
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Xsendfile和readfile区别:
http://www.laruence.com/2012/05/02/2613.html