/
SingleFileUpload.php
101 lines (86 loc) · 2.93 KB
/
SingleFileUpload.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
<?php
/**
* Created by PhpStorm.
* User: guoxiaosong
* Date: 2016/1/12
* Time: 下午2:49
*/
namespace mztest\singleFileUpload;
use mztest\singleFileUpload\SingleFileUploadAsset;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\InputWidget;
class SingleFileUpload extends InputWidget
{
public $uploadAction;
public function init()
{
parent::init();
if (!isset($this->options['class'])) {
$this->options['class'] = 'form-control';
}
if (!isset($this->options['placeholder'])) {
$this->options['placeholder'] = '点击右侧按钮上传图片,或者直接写入图片地址';
}
if (!is_array($this->uploadAction)) {
$this->uploadAction = [$this->uploadAction];
}
$this->uploadAction = Url::toRoute(ArrayHelper::merge(
['inputName' => $this->getFileInputName()],
$this->uploadAction)
);
}
public function run()
{
$view = $this->getView();
SingleFileUploadAsset::register($view);
$view->registerJs("$('#".$this->getFileInputId()."').fileupload({
url: '". $this->uploadAction ."',
dataType: 'json',
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxNumberOfFiles: 1,
maxFileSize: 2000000, // 2 MB,
start: function(e, data) {
$(this).prev('span').button('loading');
},
done: function (e, data) {
var result = data.result;
var file = data.result.files[0];
$(this).parents('.input-group').find('input[type=text]').val(file.relativeUrl);
$(this).prev('span').button('reset');
}
})");
echo $this->renderInput();
}
protected function renderInput()
{
$fileButton = '<span class="input-group-addon"><span class="fileinput-button">'
. '<i class="glyphicon glyphicon-plus"></i>'
. '<span data-loading-text="上传中...">上传图片 ...</span>'
. Html::fileInput($this->getFileInputName(), '', [
'id' => $this->getFileInputId(),
'class' => 'single-file-upload'
])
. '</span></span>';
if ($this->hasModel()) {
$input = Html::activeTextInput($this->model, $this->attribute, $this->options);
} else {
$input = Html::textInput($this->name, '', $this->options);
}
return '<div class="input-group">'. $input. $fileButton . '</div>';
}
protected function getFileInputName()
{
if ($this->hasModel()) {
$name = preg_replace('[\[|\]]', '-', Html::getInputName($this->model, $this->attribute));
} else {
$name = $this->name;
}
return '_file_'. $name;
}
protected function getFileInputId()
{
return '_file_'. $this->getId();
}
}