


yii2.0 uses Plupload to implement multi-image upload with zoom function, _PHP tutorial
yii2.0 uses Plupload to implement multi-image upload with zoom function.
This article explains the relevant code of plupload, implements ajax upload of multiple images at the same time, and then scales the image , finally display the picture and share it with everyone 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',//处理文件上传控制器 ])?>
2. commonwidgetsPlupload component
<?php namespace 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 src="/static/imghwm/default1.png" data-src="'.$path.'" class="lazy" style="max-width:90%".$path.'" / alt="yii2.0 uses Plupload to implement multi-image upload with zoom function, _PHP tutorial" ></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. backendassetsUploadAsset
Register related js
<?php namespace 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('已上传:'+file.percent+'%'); }, FileUploaded:function (up, file, result) { result = $.parseJSON(result.response); if(result.code == 0){ $('#'+buttonId).html('<img src="/static/imghwm/default1.png" data-src="'+result.path+'" class="lazy"+result.path+'" style="max-width:90%" / alt="yii2.0 uses Plupload to implement multi-image upload with zoom function, _PHP tutorial" >'); $('#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. backendassetsPluploadAsset
Register plupload related resources
<?php namespace 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 the uploaded 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. commonmodelsImageUpload
The model performs certain detection on the uploaded files, and then scales the source files according to a certain ratio
<?php namespace common\models; use yii\base\Exception; use yii\helpers\FileHelper; use yii\web\UploadedFile; class ImageUpload extends \yii\base\Object { public $fileInputName = 'file';//上传表单 file name public $savePath ;//图像保存根位置 public $allowExt = ['jpg','png','jpeg','gif','bmp'];//允许上传后缀 public $maxFileSize=1024100000;//最大大小 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;//上传文件 private $filePath;//文件路径 private $urlPath;//访问路径 private $res=false;//返回状态 private $message;//返回信息 public function getMessage(){ return $this->message; } public function getUrlPath(){ return $this->urlPath; } public function init(){ if(!$this->fileInputName) throw new Exception('fileInputName属性不能为空'); 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 = '没有权限创建'.$this->savePath; return false; } } $this->_uploadFile = UploadedFile::getInstanceByName($this->fileInputName); if(!$this->_uploadFile){ $this->message = '没有找到上传文件'; return false; } if($this->_uploadFile->error){ $this->message = '上传失败'; return false; } if(!in_array($this->extension,$this->allowExt) || !in_array($this->type,$this->allowType)){ $this->message = '该文件类型不允许上传'; return false; } if($this->_uploadFile->size> $this->maxFileSize){ $this->message = '文件过大'; 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);//缩放图片 $this->res = true; }else{ $this->res = false; } if($this->res){ $this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上传成功'; }else{ $this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上传失败'; } return $this->res; } /** * 获取文件名字 * @return null */ public function getBaseName(){ if($this->_uploadFile){ return $this->_uploadFile->baseName; }else{ return null; } } /** * 返回文件后缀 * @return null */ public function getExtension(){ if($this->_uploadFile){ return $this->_uploadFile->extension; }else{ return null; } } /** * 返回文件类型 * @return mixed */ public function getType(){ if($this->_uploadFile){ return $this->_uploadFile->type; } return null; } /** * 生成保持原图纵横比的缩略图,支持.png .jpg .gif * 缩略图类型统一为.png格式 * $srcFile 原图像文件名称 * $toFile 缩略图文件名称,为空覆盖原图像文件 * $toW 缩略图宽 * $toH 缩略图高 * @return bool */ public static function CreateThumbnail($srcFile, $toFile="", $toW=100, $toH=100) { if ($toFile == "") $toFile = $srcFile; $data = getimagesize($srcFile);//返回含有4个单元的数组,0-宽,1-高,2-图像类型,3-宽高的文本描述。 if (!$data) return false; //将文件载入到资源变量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; } //计算缩略图的宽高 $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); //新建一个真彩色图像 if ($ni) { //重采样拷贝部分图像并调整大小 可保持较好的清晰度 imagecopyresampled($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); } } 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 entire content of this article. I hope it will be helpful to everyone in learning PHP programming.
Articles you may be interested in:
- Yii implements the method of uploading files using CUploadedFile
- yii implements the method of image uploading and thumbnail generation
- Yii Combined with CKEditor to implement the image upload function
- yii uploads files or image instances
- yii uses the activeFileField control to implement the method of uploading files and images

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)