Yii2.0 uses Plupload to achieve multi-image upload with zoom function.
This article explains the relevant code of Plupload, the implementation of the AJAX multi-image upload, and then the image is scaled, the final display pictures, share for everyone to reference, the specific content as follows
1. Call Plupload in the article view
<?= \common\widgets\plupload::widget ([' Model ' = $model, ' attribute ' = ' cover_img ', ' url ' = '/file/' Upload ',//Processing file Upload Controller])?>
2. \common\widgets\plupload Components
<?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 parameter cannot be null ');} if (! $this->model) {throw new Exception (' model attribute cannot be null '); } if (! $this->attribute) {throw new Exception (' attribute attribute cannot be null '); }} public Function run () {$model = $this->model; $attribute = $this->attribute; $path = $model $attribute? $model $attribute: "/images/noimage.gif";//display article picture or default picture $this->_html.= '; $this->_html.=html::activelabel ($model, $attribute); $this->_html.=html::activehiddeninput ($model, $attribute, [' id ' = ' hidden_input ', ' value ' = ' $path]); $this->_html. = "; $this->_html.= '; 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
Registration related 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 processing Code
function Initcoverimageuploader (buttonid,contatinerid,maxfilesize,url,csrftoken) {var uploader = new Plupload. Uploader ({runtimes: ' Html5,flash,silverlight,html4 ', Browse_button:buttonid,//can pass an ID ... container:con Tatinerid,//... or DOM Element itself url:url, Flash_swf_url: ' @vendor/moxiecode/plupload/js/moxie.swf ', Silverlig Ht_xap_url: ' @vendor/moxiecode/plupload//js/moxie.xap ', filters: {max_file_size:maxfilesize, mime_types: [{t Itle: "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 (' uploaded: ' +file.percent+ '% '); }, Fileuploaded:function (up, file, result) {result = $.parsejson (result.response); if (Result.code = = 0) {$ (' # ' +buttonid). html ('); $ (' #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 ();}
5, Backend\assets\pluploadasset
Register Plupload Related Resources
<?phpnamespace backend\assets;use yii\web\assetbundle;class Pluploadasset extends assetbundle{public $sourcePath = ' @vendor/moxiecode/plupload '; Public $css = []; Public $js = [ ' js/plupload.full.min.js ',]; public $depends = [ ' Yii\web\jqueryasset ',];}
6, Filecontroller
The controller invokes the model to process the upload file and returns the result
Class Filecontroller extends basecontroller{public Function actionupload () { Yii:: $app->response->format= Response::format_json; $model = New imageupload (); $model->fileinputname = ' file '; if ($model->save ()) { return [' Code ' =>0, ' message ' = = $model->getmessage (), ' path ' = $model Geturlpath ()]; } else{ return [' Code ' =>1, ' message ' = = $model->getmessage ()];}}
7, Common\models\imageupload
The upload file is detected in the model, then the source file is scaled in a certain proportion.
<?phpnamespace common\models;use yii\base\exception;use yii\helpers\filehelper;use yii\web\UploadedFile;class Imageupload extends \yii\base\object{public $fileInputName = ' file ';//upload Form file name public $savePath;//Image Save root location public $ Allowext = [' jpg ', ' png ', ' jpeg ', ' gif ', ' BMP '];//allow upload suffix public $maxFileSize =1024100000;//maximum size public $allowType = [' Image /jpeg ', ' image/bmp ', ' image/gif ', ' image/png ', ' image/pjpeg ', ' image/bmp ', ' image/gif ', ' image/x-png ', ' image/pjpeg ', ' Image/bmp ', ' image/gif ', ' image/x-png ', ' image/pjpeg ', ' image/bmp ', ' image/gif ', ' image/x-png ']; Private $_uploadfile;//upload file private $filePath;//file path private $urlPath;//access Path private $res =false;//return status private $message ;//Return information public Function GetMessage () {return $this->message;} public Function Geturlpath () {return $this->urlpath ; } Public Function init () {if (! $this->fileinputname) throw new Exception (' fileinputname attribute cannot be null '); if (! $this->savepath) $this->savepath = \yii:: $app->basepath. ' /web/uploads/images '; $this-≫savepath = RTrim ($this->savepath, '/'); if (!file_exists ($this->savepath)) {if (! Filehelper::createdirectory ($this->savepath)) {$this->message = ' no permissions created '. $this->savepath; return false; }} $this->_uploadfile = Uploadedfile::getinstancebyname ($this->fileinputname); if (! $this->_uploadfile) {$this->message = ' No upload file found '; return false; } if ($this->_uploadfile->error) {$this->message = ' upload failed '; return false; } if (!in_array ($this->extension, $this->allowext) | |!in_array ($this->type, $this->allowtype)) {$this- >message = ' This file type is not allowed to be uploaded '; return false; if ($this->_uploadfile->size> $this->maxfilesize) {$this->message = ' file is too large '; return false; } $path = Date (' Y-m ', Time ()); if (!file_exists ($this->savepath. ' /'. $path)} {filehelper::createdirectory ($this->savepath. ') /'. $path); } $name = substr (\yii:: $app->security->generaterandomstring (), -4,4); $this->filepath = $this->savepath. ' /'. $path. ' /'. $this->basename. '--$name. '. $this->extension; $this->urlpath = '/uploads/images/'. $path. ' /'. $this->basename. '--$name. '. $this->extension; Public Function Save () {if ($this->_uploadfile->saveas ($this->filepath)) {$this->createthumbnail ($ This->filepath);//Zoom picture $this->res = true; }else{$this->res = false; if ($this->res) {$this->message = $this->_uploadfile->basename. '. $this->_uploadfile->extension. ' Upload success '; }else{$this->message = $this->_uploadfile->basename. '. '. $this->_uploadfile->extension. ' Upload failed '; } return $this->res; }/** * Gets the file name * @return NULL */Public Function getbasename () {if ($this->_uploadfile) {return $this->_UPLOADF ile->basename; }else{return null; }}/** * Returns the file suffix * @return null */Public Function getextension () {if ($this->_uploadfile) {return $this->_uplo adfile->extension; }else{return null; }}/** * return file type * @return MixEd */Public Function GetType () {if ($this->_uploadfile) {return $this->_uploadfile->type; } return null; }/** * Generates thumbnails that maintain the original aspect ratio, supports. png. jpg. gif * thumbnail type unified for. png format * $srcFile original image file name * $toFile thumbnail file name, empty overwrite original image file * $toW thumbnail Width * $toH thumbnail height * @return bool */public static function Createthumbnail ($srcFile, $toFile = "", $toW =100, $toH =100) {i F ($toFile = = "") $toFile = $srcFile; $data = getimagesize ($srcFile);//Returns an array containing 4 cells, 0-wide, 1-high, 2-image type, 3-wide text description. if (! $data) return false; Load file into resource variable im in switch ($data [2])//1-gif,2-jpg,3-png {case 1:if (!function_exists ("Imagecreatefromgif")) return F Alse; $im = Imagecreatefromgif ($srcFile); Break Case 2:if (!function_exists ("Imagecreatefromjpeg")) return false; $im = Imagecreatefromjpeg ($srcFile); Break Case 3:if (!function_exists ("Imagecreatefrompng")) return false; $im = Imagecreatefrompng ($srcFile); Break }//Calculate the width and height of the thumbnail $srcW = Imagesx ($im); $srcH = Imagesy ($im); $toWH = $toW/$toH; $srcWH = $srcW/$srcH; if ($toWH <= $srcWH) {$ftoW = $toW; $ftoH = (int) ($ftoW * ($srcH/$srcW)); } else {$ftoH = $toH; $ftoW = (int) ($ftoH * ($srcW/$srcH)); } if (Function_exists ("Imagecreatetruecolor")) {$ni = Imagecreatetruecolor ($ftoW, $ftoH);//Create a new True color image if ($ni) { Resample the copy portion of the image and resize it to maintain good sharpness imagecopyresampled ($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } else {//Copy part of the image and resize $ni = Imagecreate ($ftoW, $ftoH); Imagecopyresized ($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); }} else {$ni = Imagecreate ($ftoW, $ftoH); Imagecopyresized ($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } switch ($data [2])//1-gif,2-jpg,3-png {case 1:imagegif ($ni, $toFile); Break Case 2:imagejpeg ($ni, $toFile); Break Case 3:imagepng ($ni, $toFile); Break } Imagedestroy ($ni); Imagedestroy ($im); return $toFile; }}
The above is the whole content of this article, I hope that you learn PHP programming help.
Articles you may be interested in:
- Yii implementation method of uploading files using Cuploadedfile
- The method of image uploading and thumbnail generation for Yii
- Yii combined with CKEditor to achieve image upload function
- Yii upload file or picture instance
- Yii method for uploading files and pictures using Activefilefield control
http://www.bkjia.com/PHPjc/1084572.html www.bkjia.com true http://www.bkjia.com/PHPjc/1084572.html techarticle yii2.0 using Plupload to achieve multi-image upload with zoom function, this article explains the Plupload related code, the implementation of the AJAX multi-image upload, and then zoom the image, the final display pictures ...