欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-09 22:18:39
本文讲解了plupload的相关代码,实现了ajax多图同时上传,然后将图片进行缩放,最后显示图片,分享给大家供大家参考,具体内容如下 1、文章视图中调用plupload...

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

1、文章视图中调用plupload

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

2、\common\widgets\plupload 组件

<?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 height="50" src="'.$path.'" /></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、backend\assets\uploadasset
注册相关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处理代码

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="'+result.path+'" height="50" />');
     $('#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
注册plupload相关资源

<?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
控制器调用模型处理上传文件,并且返回结果

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
模型中对上传文件做了一定的检测,然后将源文件按照一定的比例进行缩放

<?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;
 }
}

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