-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathFileUploadAction.php
241 lines (217 loc) · 6.5 KB
/
FileUploadAction.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
<?php
/**
* author : forecho <[email protected]>
* createTime : 2019-08-04 09:16
* description:
*/
namespace yiier\AliyunOSS;
use Yii;
use yii\base\Action;
use yii\base\DynamicModel;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\web\Response;
use yii\web\UploadedFile;
class FileUploadAction extends Action
{
/**
* 上传文件的 file 参数名
* @var string
*/
public $fileParam = 'filename';
/**
* @link https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation
* @var array
*/
public $validationRules = [
[
'file',
'file',
'extensions' => ['png', 'jpeg', 'jpg', 'gif', 'webp', 'bmp'],
'checkExtensionByMimeType' => false,
'mimeTypes' => 'image/*',
'maxSize' => 5 * 1024 * 1024
]
];
/**
* 文件名生成的方式,默认用 md5
* @var callable
*/
public $fileSaveNameCallback;
/**
* 文件保存的方法,默认用 UploadedFile::saveAs()
* @var callable
*/
public $saveFileCallback;
/**
* 返回结果回调函数
* @var callable
*/
public $returnCallback;
/**
* @var bool
*/
public $normalizePath = 'auto';
/**
* 文件保存路径
* @var string
*/
public $savePath = '@webroot/uploads';
/**
* 文件显示的路径
* @var string
*/
public $webPath = '@web/uploads';
/**
* @var string
*/
public $uploadSaveErrorMassage = '上传的文件保存失败';
/**
* 是否保留本地文件
* @var bool
*/
public $keepLocalFile = false;
/**
* @inheritdoc
*/
public function init()
{
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->request->enableCsrfValidation = false;
if ($this->normalizePath === 'auto') {
$this->normalizePath = strpos($this->savePath, '..') !== false;
}
parent::init();
}
/**
* @inheritdoc
*
* @return array
* @throws InvalidConfigException
*/
public function run()
{
$uploadedFiles = UploadedFile::getInstancesByName($this->fileParam);
$resultData = [];
foreach ($uploadedFiles as $key => $uploadedFile) {
$validationModel = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules);
if ($validationModel->hasErrors()) {
$errorMassage = $validationModel->getFirstError('file');
break;
}
try {
$filename = $this->getFileName($uploadedFile);
if (!$this->saveFile($uploadedFile, $filename)) {
throw new \Exception($this->uploadSaveErrorMassage);
}
$this->uploadOSS($filename);
if (!$this->keepLocalFile) {
$this->deleteLocalFile($filename);
}
$resultData[$key] = $this->getFullFilename($filename, $this->webPath);
continue;
} catch (\Exception $e) {
Yii::error($e, 'upload error');
$errorMassage = $e->getMessage();
break;
}
}
if (isset($errorMassage)) {
// 失败了要删除之前的
foreach ($resultData as $resultDatum) {
$this->deleteFile($resultDatum);
}
return $this->parseResult(500, $errorMassage);
}
return $this->parseResult(0, '', $resultData);
}
/**
* @param $uploadedFile UploadedFile
* @param string $filename
* @return bool
* @throws \yii\base\Exception
*/
protected function saveFile(UploadedFile $uploadedFile, string $filename)
{
$filename = $this->getFullFilename($filename, $this->savePath);
if ($this->saveFileCallback && is_callable($this->saveFileCallback)) {
return call_user_func($this->saveFileCallback, $filename, $uploadedFile, $this);
}
FileHelper::createDirectory(dirname($filename));
return $uploadedFile->saveAs($filename);
}
/**
* @param $uploadedFile UploadedFile
* @return string
* @throws \Exception
*/
private function getFileName($uploadedFile)
{
if ($this->fileSaveNameCallback && is_callable($this->fileSaveNameCallback)) {
$filename = call_user_func($this->fileSaveNameCallback, $uploadedFile, $this);
} else {
$filename = md5(microtime() . random_int(10000, 99999));
}
if (strpos($filename, '.') === false) {
$filename .= '.' . $uploadedFile->getExtension();
}
return $filename;
}
/**
* @param $filename
* @param $path
* @return bool|string
*/
protected function getFullFilename($filename, $path)
{
$filename = Yii::getAlias(rtrim($path, '/') . '/' . $filename);
if ($this->normalizePath) {
return FileHelper::normalizePath($filename);
}
return $filename;
}
/**
* Parse result
* @param int $code
* @param string $message
* @param array $data
* @return array
*/
protected function parseResult(int $code, $message = '', $data = [])
{
if ($this->returnCallback && is_callable($this->returnCallback)) {
return call_user_func($this->returnCallback, $code, $message, $data);
}
return ['code' => $code, 'massage' => $message, 'data' => $data];
}
/**
* @param string $fileWebName
* @throws InvalidConfigException
*/
protected function deleteFile(string $fileWebName)
{
$fileWebNames = explode('/', $fileWebName);
$this->deleteLocalFile(end($fileWebNames));
$oss = \Yii::$app->get('oss');
$oss->delete(ltrim($fileWebName, '/'));
}
/**
* @param string $filename
*/
protected function deleteLocalFile(string $filename)
{
$fileAbsoluteName = $this->getFullFilename($filename, $this->savePath);
@unlink($fileAbsoluteName);
}
/**
* @param string $filename
* @throws InvalidConfigException
*/
public function uploadOSS(string $filename)
{
$fileAbsoluteName = $this->getFullFilename($filename, $this->savePath);
$fileWebName = $this->getFullFilename($filename, $this->webPath);
$oss = \Yii::$app->get('oss');
$oss->upload(ltrim($fileWebName, '/'), $fileAbsoluteName);
}
}