当前位置:Gxlcms > PHP教程 > yii2.0使用Plupload实现带缩放功能的多图上传_PHP

yii2.0使用Plupload实现带缩放功能的多图上传_PHP

时间:2021-07-01 10:21:17 帮助过:32人阅读

本文讲解了plupload的相关代码,实现了ajax多图同时上传,然后将图片进行缩放,最后显示图片,分享给大家供大家参考,具体内容如下

1、文章视图中调用Plupload

  1. <?= \common\widgets\Plupload::widget([
  2. 'model'=>$model,
  3. 'attribute'=>'cover_img',
  4. 'url'=>'/file/upload',//处理文件上传控制器
  5. ])?>

2、\common\widgets\Plupload 组件

  1. <?php
  2. namespace common\widgets;
  3. use backend\assets\UploadAsset;
  4. use yii;
  5. use yii\helpers\Html;
  6. use yii\base\Exception;
  7. class Plupload extends yii\bootstrap\Widget{
  8. public $model;
  9. public $attribute;
  10. public $name;
  11. public $url;
  12. private $_html;
  13. public function init(){
  14. parent::init();
  15. if(!$this->url){
  16. throw new Exception('url参数不能为空');
  17. }
  18. if(!$this->model){
  19. throw new Exception('model属性不能为空');
  20. }
  21. if(!$this->attribute){
  22. throw new Exception('attribute属性不能为空');
  23. }
  24. }
  25. public function run(){
  26. $model = $this->model;
  27. $attribute = $this->attribute;
  28. $path = $model->$attribute?$model->$attribute:"/images/noimage.gif";//显示文章图片或者默认图片
  29. $this->_html.='';
  30. $this->_html.=Html::activeLabel($model,$attribute);
  31. $this->_html.=Html::activeHiddenInput($model,$attribute,['id'=>'hidden_input','value'=>$path]);
  32. $this->_html .= '<img height="50" src="https://www.gxlcms.com/'.$path.'">';
  33. $this->_html.=' ';
  34. UploadAsset::register($this->view);
  35. $this->view->registerJs(
  36. '$(function(){
  37. initCoverImageUploader("pickfiles","container","2mb","'.$this->url.'","'.Yii::$app->request->getCsrfToken().'");
  38. });'
  39. );
  40. return $this->_html;
  41. }
  42. }

3、backend\assets\UploadAsset
注册相关js

  1. <?php
  2. namespace backend\assets;
  3. use yii\web\AssetBundle;
  4. class UploadAsset extends AssetBundle
  5. {
  6. public $basePath = '@webroot';
  7. public $baseUrl = '@web';
  8. public $css = [
  9. ];
  10. public $js = [
  11. 'js/upload.js'
  12. ];
  13. public $depends = [
  14. 'backend\assets\PluploadAsset',
  15. ];
  16. }

4、js/upload.js
ajax处理代码

  1. function initCoverImageUploader(buttonId,contatinerId,maxFileSize,url,csrfToken){
  2. var uploader = new plupload.Uploader({
  3. runtimes : 'html5,flash,silverlight,html4',
  4. browse_button :buttonId, // you can pass an id...
  5. container: contatinerId, // ... or DOM Element itself
  6. url : url,
  7. flash_swf_url : '@vendor/moxiecode/plupload/js/Moxie.swf',
  8. silverlight_xap_url : '@vendor/moxiecode/plupload//js/Moxie.xap',
  9. filters : {
  10. max_file_size : maxFileSize,
  11. mime_types: [
  12. {title : "Image files", extensions : "jpg,gif,png"},
  13. {title : "Zip files", extensions : "zip"}
  14. ]
  15. },
  16. multipart_params:{
  17. '_csrf':csrfToken
  18. },
  19. init: {
  20. FilesAdded: function(up, files) {
  21. uploader.start();
  22. },
  23. UploadProgress: function(up, file) {
  24. $('#'+contatinerId+' p').text('已上传:'+file.percent+'%');
  25. },
  26. FileUploaded:function (up, file, result) {
  27. result = $.parseJSON(result.response);
  28. if(result.code == 0){
  29. $('#'+buttonId).html('<img src="https://www.gxlcms.com/'+result.path+'" height="50">');
  30. $('#hidden_input').val(result.path);
  31. //console.log(result.message);
  32. }
  33. },
  34. Error: function(up, err) {
  35. document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
  36. }
  37. }
  38. });
  39. uploader.init();
  40. }

5、backend\assets\PluploadAsset
注册plupload相关资源

  1. <?php
  2. namespace backend\assets;
  3. use yii\web\AssetBundle;
  4. class PluploadAsset extends AssetBundle
  5. {
  6. public $sourcePath = '@vendor/moxiecode/plupload';
  7. public $css = [
  8. ];
  9. public $js = [
  10. 'js/plupload.full.min.js',
  11. ];
  12. public $depends = [
  13. 'yii\web\JqueryAsset',
  14. ];
  15. }

6、FileController
控制器调用模型处理上传文件,并且返回结果

  1. class FileController extends BaseController
  2. {
  3. public function actionUpload(){
  4. Yii::$app->response->format=Response::FORMAT_JSON;
  5. $model = New ImageUpload();
  6. $model->fileInputName = 'file';
  7. if($model->save()){
  8. return ['code'=>0,'message'=>$model->getMessage(),'path'=>$model->getUrlPath()];
  9. }else{
  10. return ['code'=>1,'message'=>$model->getMessage()];
  11. }
  12. }
  13. }

7、common\models\ImageUpload
模型中对上传文件做了一定的检测,然后将源文件按照一定的比例进行缩放

  1. <?php
  2. namespace common\models;
  3. use yii\base\Exception;
  4. use yii\helpers\FileHelper;
  5. use yii\web\UploadedFile;
  6. class ImageUpload extends \yii\base\Object
  7. {
  8. public $fileInputName = 'file';//上传表单 file name
  9. public $savePath ;//图像保存根位置
  10. public $allowExt = ['jpg','png','jpeg','gif','bmp'];//允许上传后缀
  11. public $maxFileSize=1024100000;//最大大小
  12. 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'];
  13. private $_uploadFile;//上传文件
  14. private $filePath;//文件路径
  15. private $urlPath;//访问路径
  16. private $res=false;//返回状态
  17. private $message;//返回信息
  18. public function getMessage(){
  19. return $this->message;
  20. }
  21. public function getUrlPath(){
  22. return $this->urlPath;
  23. }
  24. public function init(){
  25. if(!$this->fileInputName) throw new Exception('fileInputName属性不能为空');
  26. if(!$this->savePath) $this->savePath = \Yii::$app->basePath.'/web/uploads/images';
  27. $this->savePath = rtrim($this->savePath,'/');
  28. if(!file_exists($this->savePath)){
  29. if(! FileHelper::createDirectory($this->savePath)){
  30. $this->message = '没有权限创建'.$this->savePath;
  31. return false;
  32. }
  33. }
  34. $this->_uploadFile = UploadedFile::getInstanceByName($this->fileInputName);
  35. if(!$this->_uploadFile){
  36. $this->message = '没有找到上传文件';
  37. return false;
  38. }
  39. if($this->_uploadFile->error){
  40. $this->message = '上传失败';
  41. return false;
  42. }
  43. if(!in_array($this->extension,$this->allowExt) || !in_array($this->type,$this->allowType)){
  44. $this->message = '该文件类型不允许上传';
  45. return false;
  46. }
  47. if($this->_uploadFile->size> $this->maxFileSize){
  48. $this->message = '文件过大';
  49. return false;
  50. }
  51. $path = date('Y-m',time());
  52. if(!file_exists($this->savePath.'/'.$path)){
  53. FileHelper::createDirectory($this->savePath.'/'.$path);
  54. }
  55. $name = substr(\Yii::$app->security->generateRandomString(),-4,4);
  56. $this->filePath = $this->savePath.'/https://www.gxlcms.com/'.$path.'/'.$this->baseName.'--'.$name.'.'.$this->extension;
  57. $this->urlPath = '/uploads/images/https://www.gxlcms.com/'.$path.'/'.$this->baseName.'--'.$name.'.'.$this->extension;
  58. }
  59. public function save(){
  60. if($this->_uploadFile->saveAs($this->filePath)){
  61. $this->CreateThumbnail($this->filePath);//缩放图片
  62. $this->res = true;
  63. }else{
  64. $this->res = false;
  65. }
  66. if($this->res){
  67. $this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上传成功';
  68. }else{
  69. $this->message = $this->_uploadFile->baseName.'.'.$this->_uploadFile->extension.'上传失败';
  70. }
  71. return $this->res;
  72. }
  73. /**
  74. * 获取文件名字
  75. * @return null
  76. */
  77. public function getBaseName(){
  78. if($this->_uploadFile){
  79. return $this->_uploadFile->baseName;
  80. }else{
  81. return null;
  82. }
  83. }
  84. /**
  85. * 返回文件后缀
  86. * @return null
  87. */
  88. public function getExtension(){
  89. if($this->_uploadFile){
  90. return $this->_uploadFile->extension;
  91. }else{
  92. return null;
  93. }
  94. }
  95. /**
  96. * 返回文件类型
  97. * @return mixed
  98. */
  99. public function getType(){
  100. if($this->_uploadFile){
  101. return $this->_uploadFile->type;
  102. }
  103. return null;
  104. }
  105. /**
  106. * 生成保持原图纵横比的缩略图,支持.png .jpg .gif
  107. * 缩略图类型统一为.png格式
  108. * $srcFile 原图像文件名称
  109. * $toFile 缩略图文件名称,为空覆盖原图像文件
  110. * $toW 缩略图宽
  111. * $toH 缩略图高
  112. * @return bool
  113. */
  114. public static function CreateThumbnail($srcFile, $toFile="", $toW=100, $toH=100)
  115. {
  116. if ($toFile == "") $toFile = $srcFile;
  117. $data = getimagesize($srcFile);//返回含有4个单元的数组,0-宽,1-高,2-图像类型,3-宽高的文本描述。
  118. if (!$data) return false;
  119. //将文件载入到资源变量im中
  120. switch ($data[2]) //1-GIF,2-JPG,3-PNG
  121. {
  122. case 1:
  123. if(!function_exists("imagecreatefromgif")) return false;
  124. $im = imagecreatefromgif($srcFile);
  125. break;
  126. case 2:
  127. if(!function_exists("imagecreatefromjpeg")) return false;
  128. $im = imagecreatefromjpeg($srcFile);
  129. break;
  130. case 3:
  131. if(!function_exists("imagecreatefrompng")) return false;
  132. $im = imagecreatefrompng($srcFile);
  133. break;
  134. }
  135. //计算缩略图的宽高
  136. $srcW = imagesx($im);
  137. $srcH = imagesy($im);
  138. $toWH = $toW / $toH;
  139. $srcWH = $srcW / $srcH;
  140. if ($toWH <= $srcWH) {
  141. $ftoW = $toW;
  142. $ftoH = (int)($ftoW * ($srcH / $srcW));
  143. } else {
  144. $ftoH = $toH;
  145. $ftoW = (int)($ftoH * ($srcW / $srcH));
  146. }
  147. if (function_exists("imagecreatetruecolor")) {
  148. $ni = imagecreatetruecolor($ftoW, $ftoH); //新建一个真彩色图像
  149. if ($ni) {
  150. //重采样拷贝部分图像并调整大小 可保持较好的清晰度
  151. imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
  152. } else {
  153. //拷贝部分图像并调整大小
  154. $ni = imagecreate($ftoW, $ftoH);
  155. imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
  156. }
  157. } else {
  158. $ni = imagecreate($ftoW, $ftoH);
  159. imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
  160. }
  161. switch ($data[2]) //1-GIF,2-JPG,3-PNG
  162. {
  163. case 1:
  164. imagegif($ni, $toFile);
  165. break;
  166. case 2:
  167. imagejpeg($ni, $toFile);
  168. break;
  169. case 3:
  170. imagepng($ni, $toFile);
  171. break;
  172. }
  173. ImageDestroy($ni);
  174. ImageDestroy($im);
  175. return $toFile;
  176. }
  177. }

以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。

人气教程排行