* @created Sep 11, 2019 */ class Upload extends InputWidget { /** * @var string * 上传url */ public $url; /** * @var bool * 是否支持多图 */ public $multiple; /** * @var string * 文件保存后ajax异步操作(如操作数据库) */ public $afterSave; /** * @var bool * 显示预览 */ public $showPreviews; /** * @var integer * 最大数量 */ public $maxCount; /** * @var string * 支持上传的文件类型 */ public $acceptFile; /** * @var int * 最大现在尺寸(kB) */ public $maxSize; /** * @var array * 预览设置 */ public $previewConfig; /** * @var string * 删除图片 */ public $deleteUrl; /** * @var bool * 显示删除按钮 */ public $showDelete; /** * @var int * 预览框大小 */ public $statusBarWidth; /** * @var int * 拉拽框大小 */ public $dragdropWidth; /** * @throws NotFoundHttpException * @throws \yii\base\InvalidConfigException * 初始化参数 */ public function init() { parent::init(); if (!$this->url) { throw new NotFoundHttpException('(upload) 必须配置上传url'); } if (isset($this->previewConfig['url'])) { $this->previewConfig['height'] = $this->previewConfig['height'] ?? '80px'; $this->previewConfig['width'] = $this->previewConfig['width'] ?? '80px'; } $this->showPreviews = $this->previewConfig['url'] ? 'true' : 'false';//默认不显示预览 $this->showPreviews = $this->showPreviews ?: 'false';//默认关闭预览 $this->statusBarWidth = $this->statusBarWidth ?: 300;//默认关闭预览 $this->dragdropWidth = $this->dragdropWidth ?: 800;//默认关闭预览 $this->acceptFile = $this->acceptFile ?: '*';//默认无限制文件类型 $this->maxCount = $this->maxCount ?: 10;//默认数量限制十张图 $this->showDelete = $this->deleteUrl ? 'true' : 'false';//默认不显示删除按钮 $this->maxSize = $this->maxSize ? $this->maxSize *= 1024 : 2 * 1024 * 1024;//默认限制2M大小; } /** * @return string * 执行 */ public function run() { $this->registerAsset(); return $this->renderUploadHtml(); } /** * 注册js和css */ protected function registerAsset() { $view = $this->getView(); UploadAsset::register($view); $js = <<< SCRIPT $("#upload-file").uploadFile({ url:"upload", returnType: "json", multiple:true, dragDrop:true, fileName:"file", statusBarWidth:{$this->statusBarWidth}, dragdropWidth:{$this->dragdropWidth}, dragDropStr:"拖动上传", sizeErrorStr:"超过最大尺寸限制", maxFileCountErrorStr:"超过最大上传数量", uploadErrorStr:"上传失败", maxFileCount:"{$this->acceptFile}", maxFileCount:{$this->maxCount}, maxFileSize:{$this->maxSize}, showPreview:{$this->showPreviews}, previewHeight:"{$this->previewConfig['height']}", previewWidth:"{$this->previewConfig['width']}", showDelete: {$this->showDelete}, onSuccess: function (files, data) { $.ajax({ url: "{$this->afterSave}", dataType: "json", data: {data: data, fileName: files}, }); }, onLoad:function(obj) { $.ajax({ cache: false, url: "{$this->previewConfig['url']}", dataType: "json", success: function(data) { for(var i=0;ideleteUrl}", {op: "delete",name: data[i]}, function (resp,textStatus, jqXHR) { }); } pd.statusbar.hide(); //You choice. }, }); SCRIPT; $view->registerJs($js); } /** * @return string * 渲染html */ protected function renderUploadHtml() { return '
Upload
Drag & Drop Files
'; } }