当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-30 21:53:06 浏览: 评论:0 

本文讲解了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.  
  4. use backend\assets\UploadAsset; 
  5. use yii; 
  6. use yii\helpers\Html; 
  7. use yii\base\Exception; 
  8.  
  9. class Plupload extends yii\bootstrap\Widget{ 
  10.  public $model; 
  11.  public $attribute; 
  12.  public $name; 
  13.  public $url; 
  14.  
  15.  private $_html; 
  16.  
  17.  
  18.  public function init(){ 
  19.   parent::init(); 
  20.  if(!$this->url){ 
  21.  throw new Exception('url参数不能为空'); 
  22.  } 
  23.   if(!$this->model){ 
  24.    throw new Exception('model属性不能为空'); 
  25.   } 
  26.   if(!$this->attribute){ 
  27.    throw new Exception('attribute属性不能为空'); 
  28.   } 
  29.  } 
  30.  public function run(){ 
  31.   $model = $this->model; 
  32.   $attribute = $this->attribute; 
  33.   $path = $model->$attribute?$model->$attribute:"/images/noimage.gif";//显示文章图片或者默认图片 
  34.   $this->_html.='<div class="form-group field-article-author" id="container">'; 
  35.   $this->_html.=Html::activeLabel($model,$attribute); 
  36.   $this->_html.=Html::activeHiddenInput($model,$attribute,['id'=>'hidden_input','value'=>$path]); 
  37.   $this->_html .= '<div id="pickfiles" style="height:50px;min-width:50px;max-width: 300px;overflow: hidden;"><img height="50" src="'.$path.'" /></div>'; 
  38.   $this->_html.='</div> '; 
  39.   UploadAsset::register($this->view); 
  40.  $this->view->registerJs( 
  41.  '$(function(){ 
  42.     initCoverImageUploader("pickfiles","container","2mb","'.$this->url.'","'.Yii::$app->request->getCsrfToken().'"); 
  43.    });' 
  44.  ); 
  45.  
  46.   return $this->_html; 
  47.  } 
  48.  
  49. } 

3、backend\assets\UploadAsset

注册相关js

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

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.  
  10.   filters : { 
  11.    max_file_size : maxFileSize, 
  12.    mime_types: [ 
  13.     {title : "Image files", extensions : "jpg,gif,png"}, 
  14.     {title : "Zip files", extensions : "zip"} 
  15.    ] 
  16.   }, 
  17.   multipart_params:{ 
  18.    '_csrf':csrfToken 
  19.   }, 
  20.   init: { 
  21.    FilesAdded: function(up, files) { 
  22.     uploader.start(); 
  23.    }, 
  24.    UploadProgress: function(up, file) { 
  25.     $('#'+contatinerId+' p').text('已上传:'+file.percent+'%'); 
  26.    }, 
  27.    FileUploaded:function (up, file, result) { 
  28.     result = $.parseJSON(result.response); 
  29.     if(result.code == 0){ 
  30.      $('#'+buttonId).html('<img src="'+result.path+'" height="50" />'); 
  31.      $('#hidden_input').val(result.path); 
  32.      //console.log(result.message); 
  33.     } 
  34.    }, 
  35.    Error: function(up, err) { 
  36.     document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); 
  37.    } 
  38.   } 
  39.  }); 
  40.  
  41.  uploader.init(); 
  42. } 

5、backend\assets\PluploadAsset

注册plupload相关资源

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

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.  
  14. } 

7、common\models\ImageUpload

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

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

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

Tags: yii2 0 Plupload

分享到: