本文讲解了plupload的相关代码,实现了ajax多图同时上传,然后将图片进行缩放,最后显示图片,分享给大家供大家参考,具体内容如下
1、文章视图中调用Plupload
<?= /common/widgets/Plupload::widget([ 'model'=>$model, 'attribute'=>'cover_img', 'url'=>'/file/upload',//处理文件上传控制器])?>
2、/common/widgets/Plupload 组件
<?phpnamespace common/widgets;use backend/assets/UploadAsset;use yii;use yii/helpers/Html;use yii/base/Exception;class Plupload extends yii/bootstrap/Widget{ public $model; public $attribute; public $name; public $url; private $_html; public function init(){ parent::init(); if(!$this->url){ throw new Exception('url参数不能为空'); } if(!$this->model){ throw new Exception('model属性不能为空'); } if(!$this->attribute){ throw new Exception('attribute属性不能为空'); } } public function run(){ $model = $this->model; $attribute = $this->attribute; $path = $model->$attribute?$model->$attribute:"/images/noimage.gif";//显示文章图片或者默认图片 $this->_html.='<div class="form-group field-article-author" id="container">'; $this->_html.=Html::activeLabel($model,$attribute); $this->_html.=Html::activeHiddenInput($model,$attribute,['id'=>'hidden_input','value'=>$path]); $this->_html .= '<div id="pickfiles" style="height:50px;min-width:50px;max-width: 300px;overflow: hidden;"><img height="50" src="'.$path.'" /></div>'; $this->_html.='</div> '; UploadAsset::register($this->view); $this->view->registerJs( '$(function(){ initCoverImageUploader("pickfiles","container","2mb","'.$this->url.'","'.Yii::$app->request->getCsrfToken().'"); });' ); return $this->_html; }}
3、backend/assets/UploadAsset
注册相关js
<?phpnamespace backend/assets;use yii/web/AssetBundle;class UploadAsset extends AssetBundle{ public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ ]; public $js = [ 'js/upload.js' ]; public $depends = [ 'backend/assets/PluploadAsset', ];}
4、js/upload.js
ajax处理代码
function initCoverImageUploader(buttonId,contatinerId,maxFileSize,url,csrfToken){ var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight,html4', browse_button :buttonId, // you can pass an id... container: contatinerId, // ... or DOM Element itself url : url, flash_swf_url : '@vendor/moxiecode/plupload/js/Moxie.swf', silverlight_xap_url : '@vendor/moxiecode/plupload//js/Moxie.xap', filters : { max_file_size : maxFileSize, mime_types: [ {title : "Image files", extensions : "jpg,gif,png"}, {title : "Zip files", extensions : "zip"} ] }, multipart_params:{ '_csrf':csrfToken }, init: { FilesAdded: function(up, files) { uploader.start(); }, UploadProgress: function(up, file) { $('#'+contatinerId+' p').text('已上传:'+file.percent+'%'); }, FileUploaded:function (up, file, result) { result = $.parseJSON(result.response); if(result.code == 0){ $('#'+buttonId).html('<img src="'+result.path+'" height="50" />'); $('#hidden_input').val(result.path); //console.log(result.message); } }, Error: function(up, err) { document.getElementById('console').appendChild(document.createTextNode("/nError #" + err.code + ": " + err.message)); } } }); uploader.init();}
新闻热点
疑难解答