FileController.class.php
2.64 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/**
* 【后台】下载中心下载文件
* FileController.class.php
* @author:heyuelong
* @date:2018年4月18日16:28:41
*/
namespace Frontend\Controller\Export;
use Common\Common\ExportDownload;
use Common\Service\DownloadService;
use Org\Net\PHPZip;
class FileController extends \Common\Controller\Frontend\AbstractController
{
protected $_require_login = false;
public function Index()
{
$id = I('get.id');
// 实例化
$service = new DownloadService();
// 获取详情
$info = $service->get($id);
// 初始化扩展后缀
$ext = '.xls';
if (ExportDownload::ZIP_TYPE == $info['type']) {
$phpzip = new PHPZip();
// 组装压缩文件名称
$filename = get_sitedir() . microtime(true) . '.zip';
// 打包文件
$phpzip->zipDir($info['url'], $filename, false);
$ext = '.zip';
// 下载文件
$this->down_load($info, $filename, $ext);
// 删除文件
unlink($filename);
exit;
} elseif (ExportDownload::PDF_TYPE == $info['type']) {
$ext = '.pdf';
}
$filename = $info['url'];
// 下载文件
$this->down_load($info, $filename, $ext);
exit;
}
/**
* 下载文件功能
* @param array $info
* @param string $filePath 文件地址
* @param string $ext 文件后缀
*/
protected function down_load($info = [], $filePath = '', $ext = '.xls')
{
// 文件下载
if (!file_exists($filePath)) {
exit("下载失败");
}
$filename = $info['title'] . $ext;
$fileNameEncode = urlencode($filename);
$fileNameEncode = str_replace('+', '%20', $fileNameEncode);
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
if (stripos($userAgent, 'Firefox') !== false) {
$dispositionFileName = 'filename*="utf8\'\'' . $filename . '"';
} else {
$dispositionFileName = 'filename="' . $fileNameEncode . '"';
}
unset($filename, $fileNameEncode);
$file = fopen($filePath, "r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: " . filesize($filePath));
Header("Content-Disposition: attachment; {$dispositionFileName}");
echo fread($file, filesize($filePath));
$buffer = 1024;
while (!feof($file)) {
$file_data = fread($file, $buffer);
echo $file_data;
}
fclose($file);
}
}