-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploaderAction.php
97 lines (88 loc) · 2.49 KB
/
UploaderAction.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
<?php namespace lxpgw\webuploader;
use Yii;
use yii\base\Action;
use yii\helpers\ArrayHelper;
use yii\validators\FileValidator;
use yii\web\Response;
use yii\web\UploadedFile;
/**
* The upload action for webuploader
*
* @package lxpgw\webuploader
* @version 0.1.0
*/
class UploaderAction extends Action
{
/**
* The file name
* @var string
*/
public $fileInputName = 'file';
/**
* The options passded to FileValidator
* @var array
*/
public $fileValidation = [];
/**
* The target directory to store the file, support path alias
* @var string
*/
public $targetDirectory = '@webroot/upload';
/**
* The base url of the uploaded file
* @var string
*/
public $baseUrl = '@web/upload';
/**
* The file name to save
* @var string|callable
*/
public $fileName;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->targetDirectory = Yii::getAlias($this->targetDirectory);
if (is_callable($this->fileName)) {
$this->fileName = call_user_func($this->fileName, $this);
}
}
/**
* @inhertidoc
*/
public function run()
{
Yii::$app->getResponse()->format = Response::FORMAT_JSON;
$file = UploadedFile::getInstanceByName($this->fileInputName);
$validationOptions = ArrayHelper::merge([
'extensions' => 'gif, jpg, png',
'maxSize' => 2 * 1024 * 1024,
], $this->fileValidation);
$validator = new FileValidator($validationOptions);
if (!$validator->validate($file, $errmsg)) {
return [
'errcode' => 1,
'errmsg' => $errmsg,
];
}
if (null === $this->fileName) {
$this->fileName = md5($file->name . time());
}
$file_path = $this->targetDirectory . DIRECTORY_SEPARATOR . $this->fileName;
if ($file->saveAs($file_path)) {
return [
'errcode' => 0,
'errmsg' => 'Uploaded successfully!',
'file' => [
'name' => $file->name,
'newFileName' => $this->fileName,
'alias' => $this->baseUrl . '/' . $this->fileName,
'uploaded' => Yii::getAlias($this->baseUrl) . '/' . $this->fileName . '?_' . $_SERVER['REQUEST_TIME'],
],
];
}
return ['errcode' => 1, 'errmsg' => 'Error occured'];
}
}