/
UploadAction.php
executable file
·298 lines (260 loc) · 8.34 KB
/
UploadAction.php
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<?php
namespace fatjiong\webuploader;
use Yii;
use yii\base\Action;
use yii\validators\FileValidator;
use yii\web\UploadedFile;
use yii\base\Exception;
class UploadAction extends Action {
/**
* The length of the CSRF token mask.
*/
const CSRF_MASK_LENGTH = 8;
/**
* save path
* @var string
*/
public $uploadBasePath = '@webroot/upload';
/**
* web url
* @var string
*/
public $uploadBaseUrl = '@web/upload';
/**
* Csrf Verify Enable
* @var bool
*/
public $csrf = false;
/**
* $this->output['fileUrl'] = $this->uploadBaseUrl . '/' . $this->filename;
* @var bool
*/
public $autoOutput = true;
/**
*
{filename} 会替换成原文件名,配置这项需要注意中文乱码问题
{rand:6} 会替换成随机数,后面的数字是随机数的位数
{time} 会替换成时间戳
{yyyy} 会替换成四位年份
{yy} 会替换成两位年份
{mm} 会替换成两位月份
{dd} 会替换成两位日期
{hh} 会替换成两位小时
{ii} 会替换成两位分钟
{ss} 会替换成两位秒
非法字符 \ : * ? " < > |
* @var string | Closure
*/
public $format = '{yyyy}{mm}{dd}/{time}{rand:6}';
/**
* file validator options
* @var []
* @see http://stuff.cebe.cc/yii2docs/yii-validators-filevalidator.html
* @example
* [
* 'maxSize' => 1000,
* 'extensions' => ['jpg', 'png']
* ]
*/
public $validateOptions = [];
/**
* file instance
* @var UploadedFile
*/
public $uploadFileInstance;
/**
* saved format filename
* image/yyyymmdd/xxx.jpg
* @var string
*/
public $filename;
/**
* saved format filename full path
* /var/www/htdocs/image/yyyymmdd/xxx.jpg
* @var string
*/
public $fullFilename;
/**
* throw yii\base\Exception will break
* @var Closure
* beforeValidate($UploadAction)
*/
public $beforeValidate;
/**
* throw yii\base\Exception will break
* @var Closure
* afterValidate($UploadAction)
*/
public $afterValidate;
/**
* throw yii\base\Exception will break
* @var Closure
* beforeSave($UploadAction)
*/
public $beforeSave;
/**
* throw yii\base\Exception will break
* @var Closure
* afterSave($filename, $fullFilename, $UploadAction)
*/
public $afterSave;
/**
* output
* @var []
*/
public $output = ['error' => false];
public function init() {
// Csrf验证
$this->initCsrf();
// 上传资源
$this->uploadFileInstance = UploadedFile::getInstanceByName('file');
// 基础上传路径
if (empty($this->uploadBasePath)) {
throw new Exception('上传目录不存在');
}
$this->uploadBasePath = Yii::getAlias($this->uploadBasePath);
$this->uploadBasePath = $this->getFilePath();
if (!empty($this->uploadBaseUrl)) {
$this->uploadBaseUrl = Yii::getAlias($this->uploadBaseUrl);
}
return parent::init();
}
// 处理默认上传路径,加上项目名
public function getFilePath()
{
$fullname = $this->uploadBasePath;
$rootPath = $_SERVER['DOCUMENT_ROOT'];
return $rootPath .'/'. $fullname;
}
public function run() {
try {
if ($this->uploadFileInstance === null) {
throw new Exception('上传方法错误');
}
if ($this->beforeValidate !== null) {
call_user_func($this->beforeValidate, $this);
}
$this->validate();
if ($this->afterValidate !== null) {
call_user_func($this->afterValidate, $this);
}
if ($this->beforeSave !== null) {
call_user_func($this->beforeSave, $this);
}
$this->save();
//auto output
if (true === $this->autoOutput) {
$this->processOutput();
}
if ($this->afterSave !== null) {
call_user_func($this->afterSave, $this);
}
} catch (Exception $e) {
$this->output['error'] = true;
$this->output['msg'] = $e->getMessage();
}
Yii::$app->response->format = 'json';
return $this->output;
}
// 保存文件
private function save() {
$filename = $this->getSaveFileNameWithNotExist();
$basePath = $this->uploadBasePath;
$fullFilename = $basePath . '/' . $filename;
$dirPath = dirname($fullFilename);
if (false === is_dir($dirPath)) {
if (false === mkdir($dirPath, 0755, true)) {
throw new Exception('mkdir fail: ' . $dirPath);
}
}
$result = $this->uploadFileInstance->saveAs($fullFilename);
if (!$result) {
throw new Exception('保存失败');
}
$this->filename = $filename;
$this->fullFilename = $fullFilename;
}
/**
* output fileUrl
*/
private function processOutput() {
$this->output['fileUrl'] = $this->uploadBaseUrl . '/' . $this->filename;
}
// 获取不曾保存的文件
private function getSaveFileNameWithNotExist() {
$retryCount = 10;
$currentCount = 0;
$basePath = $this->uploadBasePath;
$filename = '';
do {
++$currentCount;
$filename = $this->getSaveFileName();
$filepath = $basePath . DIRECTORY_SEPARATOR . $filename;
} while ($currentCount < $retryCount && file_exists($filepath));
if ($currentCount == $retryCount) {
throw new Exception('file exist dump of ' . $currentCount . ' times');
}
return $filename;
}
// 获取保存名称
private function getSaveFileName() {
if (is_callable($this->format) || is_array($this->format)) {
return call_user_func($this->format, $this);
}
//替换日期事件
$t = time();
$d = explode('-', date("Y-y-m-d-H-i-s"));
$format = $this->format;
$format = str_replace("{yyyy}", $d[0], $format);
$format = str_replace("{yy}", $d[1], $format);
$format = str_replace("{mm}", $d[2], $format);
$format = str_replace("{dd}", $d[3], $format);
$format = str_replace("{hh}", $d[4], $format);
$format = str_replace("{ii}", $d[5], $format);
$format = str_replace("{ss}", $d[6], $format);
$format = str_replace("{time}", $t, $format);
$srcName = mb_substr($this->uploadFileInstance->name, 0, mb_strpos($this->uploadFileInstance->name, '.'));
$srcName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $srcName);
$format = str_replace("{filename}", $srcName, $format);
//替换随机字符串
$randNum = rand(1, 10000000000) . rand(1, 10000000000);
$matches = [];
if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
$randNumLength = substr($randNum, 0, $matches[1]);
$format = preg_replace("/\{rand\:[\d]*\}/i", $randNumLength, $format);
}
$ext = $this->uploadFileInstance->getExtension();
return $format . '.' . $ext;
}
// 验证上传文件
private function validate() {
$file = $this->uploadFileInstance;
$error = [];
$validator = new FileValidator($this->validateOptions);
if (!$validator->validate($file, $error)) {
throw new Exception($error);
}
}
// Csrf验证
private function initCsrf() {
if (false === $this->csrf) {
Yii::$app->request->enableCsrfValidation = false;
return;
}
Yii::$app->request->enableCsrfValidation = false;
Yii::$app->request->enableCsrfCookie = false;
$session = Yii::$app->session;
$request = Yii::$app->request;
$session->open();
$sessionName = $session->getName();
$postSessionId = $request->post($sessionName);
$currentSessionId = $session->getId();
if ($currentSessionId != $postSessionId) {
$session->destroy();
}
$session->setId($postSessionId);
$session->open();
$request->enableCsrfValidation = true;
$request->validateCsrfToken();
}
}