-
Notifications
You must be signed in to change notification settings - Fork 13
/
UploadAction.php
72 lines (57 loc) · 1.85 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
<?php
namespace devgroup\dropzone;
use Yii;
use yii\base\Action;
use yii\helpers\Json;
use yii\web\HttpException;
use yii\web\UploadedFile;
class UploadAction extends Action
{
public $fileName = 'file';
public $upload = 'upload';
public $afterUploadHandler = null;
public $afterUploadData = null;
protected $uploadDir = '';
protected $uploadSrc = '';
public function init()
{
parent::init();
$this->uploadDir = Yii::getAlias('@webroot/' . $this->upload . '/');
$this->uploadSrc = Yii::getAlias('@web/' . $this->upload . '/');
}
public function setUpload($upload)
{
$this->upload = $upload;
$this->uploadDir = Yii::getAlias('@webroot/' . $this->upload . '/');
$this->uploadSrc = Yii::getAlias('@web/' . $this->upload . '/');
}
public function run()
{
$file = UploadedFile::getInstanceByName($this->fileName);
if ($file->hasError) {
throw new HttpException(500, 'Upload error');
}
$fileName = $file->name;
if (file_exists($this->uploadDir . $fileName)) {
$fileName = $file->baseName . '-' . uniqid() . '.' . $file->extension;
}
$file->saveAs($this->uploadDir . $fileName);
$response = [
'filename' => $fileName,
];
if (isset($this->afterUploadHandler)) {
$data = [
'data' => $this->afterUploadData,
'file' => $file,
'dirName' => $this->uploadDir,
'src' => $this->uploadSrc,
'filename' => $fileName,
'params' => Yii::$app->request->post(),
];
if ($result = call_user_func($this->afterUploadHandler, $data)) {
$response['afterUpload'] = $result;
}
}
return Json::encode($response);
}
}