Yii2.0 uses Plupload to implement multi-image upload with the zoom function ,. Yii2.0 uses Plupload to implement multi-image upload with the zoom function. This article describes the plupload code, implements simultaneous upload of multiple ajax images, and then scales the image, finally, the image yii2.0 uses Plupload to implement multi-image upload with the zoom function,
This article explains the plupload code, implements simultaneous upload of multiple ajax images, scales the images, displays the images, and shares them with you for your reference. the specific content is as follows:
1. call Plupload in the article view
<? = \ Common \ widgets \ Plupload: widget (['model' => $ model, 'attribute' => 'cover _ img ', 'URL' => '/file/upload', // process file upload controller])?>
2. \ common \ widgets \ Plupload component
<? Phpnamespace common \ widgets; use backend \ assets \ UploadAsset; 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 blank ');} if (! $ This-> model) {throw new Exception ('Model attribute cannot be blank ');} if (! $ This-> attribute) {throw new Exception ('attribute attribute cannot be blank ');} public function run () {$ model = $ this-> model; $ attribute = $ this-> attribute; $ path = $ model-> $ attribute? $ Model-> $ attribute: "/images/noimage.gif"; // display the article image or default image $ this-> _ html. =''; $ This-> _ html. = Html: activeLabel ($ model, $ attribute); $ this-> _ html. = Html: activeHiddenInput ($ model, $ attribute, ['id' => 'den den _ input', 'value' => $ path]); $ this-> _ html. ='
'; $ This-> _ html. =''; UploadAsset: register ($ this-> view); $ this-> view-> registerJs (' $ (function () {initCoverImageUploader ("pickfiles", "container ", "2 mb ","'. $ this-> url. '","'. yii: $ app-> request-> getCsrfToken (). '") ;});'); return $ this-> _ html ;}}
3. backend \ assets \ UploadAsset
Register 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, // 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 ('uploaded: '+ file. percent + '%');}, FileUploaded: function (up, file, result) {result = $. parseJSON (result. response); if (result. code = 0) {comment ('{'{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 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 calls the model to process uploaded files and returns results.
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 model detects the uploaded files and scales the source files according to 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; // The Root position of image storage: public $ allowExt = ['jpg ', 'PNG', 'jpeg ', 'GIF', 'bmp']; // allowed Upload suffixes: public $ maxFileSize = 1024100000; // maximum size: public $ allowType = ['image/jpeg ', 'image/bmp', 'image/GIF ', 'image/png ', 'image/pjp Eg ', '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 functi On 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 permission to create '. $ this-> savePath; return false; }}$ this-> _ uploadFile = UploadedFile: getInstanceByName ($ this-> fileInputName); if (! $ This-> _ uploadFile) {$ this-> message = 'upload File Not 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 cannot be uploaded '; return false ;} if ($ this-> _ uploadFile-> size> $ this-> maxFileSize) {$ this-> message = 'File 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-> _ upload File-> saveAs ($ this-> filePath) {$ this-> CreateThumbnail ($ this-> filePath); // scale the image $ this-> res = true ;} else {$ this-> res = false;} if ($ this-> res) {$ this-> message = $ this-> _ uploadFile-> baseName. '. '. $ this-> _ uploadFile-> extension. 'uploaded successfully';} else {$ this-> message = $ this-> _ uploadFile-> baseName. '. '. $ this-> _ uploadFile-> extension. 'upload failed';} return $ this-> res;}/*** get file name * @ return null */public function getB AseName () {if ($ this-> _ uploadFile) {return $ this-> _ uploadFile-> baseName;} else {return null ;}} /*** return file suffix * @ return null */public function getExtension () {if ($ this-> _ uploadFile) {return $ this-> _ uploadFile-> extension;} else {return null;}/*** return file type * @ return mixed */public function getType () {if ($ this-> _ uploadFile) {return $ this-> _ uploadFile-> type;} return null;}/*** generates a thumbnail that maintains the aspect ratio of the source image. supported. Png. jpg. gif * images are in. png format * $ srcFile original image file name * $ toFile thumbnail file name, blank overwrite original image file * $ toW thumbnail width * $ toH Thumbnail height * @ return bool */public static function CreateThumbnail ($ srcFile, $ toFile = "", $ toW = 100, $ toH = 100) {if ($ toFile = "") $ toFile = $ srcFile; $ data = getimagesize ($ srcFile ); // return an array containing four units, 0-width, 1-height, 2-image type, and 3-width text description. If (! $ Data) return false; // load the file to the resource variable im switch ($ data [2]) // 1-GIF, 2-JPG, 3-PNG {case 1: if (! Function_exists ("imagecreatefromgif") return false; $ 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 true color image if ($ ni) {// re-sample and copy part of the image and adjust the size to maintain a better definition of imagecopyresampled ($ ni, $ im, 0, 0, 0, 0, $ ftoW, $ ftoH, $ srcW, $ srcH);} else {// Copy part of the image and resize it $ 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 all the content of this article. I hope it will help you learn php programming.
Articles you may be interested in:
- Yii implements the file upload method using CUploadedFile
- Yii: How to upload images and generate thumbnails
- Yii uses CKEditor to upload images
- Yii upload files or image instances
- Yii uses the activeFileField control to upload files and images
This article explains the plupload code, implements simultaneous upload of multiple ajax images, scales the image, and displays the image...