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


Posted in PHP onDecember 22, 2015

本文讲解了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程序设计有所帮助。

PHP 相关文章推荐
也谈php网站在线人数统计
Apr 09 PHP
PHP CURL模拟GET及POST函数代码
Apr 25 PHP
在Windows系统上安装PHP运行环境文字教程
Jul 19 PHP
php中设置index.php文件为只读的方法
Feb 06 PHP
PHP 输出URL的快捷方式示例代码
Sep 22 PHP
ThinkPHP做文字水印时提示call an undefined function exif_imagetype()解决方法
Oct 30 PHP
THINKPHP项目开发中的日志记录实例分析
Dec 01 PHP
php图片的二进制转换实现方法
Dec 15 PHP
php为字符串前后添加指定数量字符的方法
May 04 PHP
PHP生成唯一订单号
Jul 05 PHP
phpcms中的评论样式修改方法
Oct 21 PHP
PHP命名空间与自动加载机制的基础介绍
Aug 25 PHP
PHP输入流php://input实例讲解
Dec 22 #PHP
服务器迁移php版本不同可能诱发的问题
Dec 22 #PHP
php上传图片并压缩的实现方法
Dec 22 #PHP
PHP实现图片上传并压缩
Dec 22 #PHP
Linux系统中设置多版本PHP共存配合Nginx服务器使用
Dec 21 #PHP
在Mac OS上搭建Nginx+PHP+MySQL开发环境的教程
Dec 21 #PHP
Linux下从零开始安装配置Nginx服务器+PHP开发环境
Dec 21 #PHP
You might like
php数组函数序列之array_slice() - 在数组中根据条件取出一段值,并返回
2011/11/07 PHP
php获取301跳转URL简单实例
2013/12/16 PHP
ThinkPHP3.1.x修改成功与失败跳转页面的方法
2017/09/29 PHP
PHP实现的ID混淆算法类与用法示例
2018/08/10 PHP
js获取单选按钮的数据
2006/11/27 Javascript
jquery.validate使用攻略 第三部
2010/07/01 Javascript
javascript从右边截取指定字符串的三种实现方法
2013/11/29 Javascript
jquery选择checked在ie8普通模式下的问题
2014/02/12 Javascript
javascript匿名函数应用示例介绍
2014/03/07 Javascript
浅谈js中的in-for循环
2016/06/28 Javascript
浅谈jQuery中ajaxPrefilter的应用
2016/08/01 Javascript
jquery css实现邮箱自动补全
2016/11/14 Javascript
浅谈JavaScript的计时器对象
2016/12/26 Javascript
element vue Array数组和Map对象的添加与删除操作
2018/11/14 Javascript
微信小程序如何修改本地缓存key中单个数据的详解
2019/04/26 Javascript
JavaScript实现更换背景图片
2019/10/18 Javascript
基于Element封装一个表格组件tableList的使用方法
2020/06/29 Javascript
[56:35]DOTA2上海特级锦标赛C组小组赛#1 OG VS Archon第二局
2016/02/27 DOTA
[49:27]2018DOTA2亚洲邀请赛 4.4 淘汰赛 TNC vs VG 第一场
2018/04/05 DOTA
详解Python中的strftime()方法的使用
2015/05/22 Python
Python 实现随机数详解及实例代码
2017/04/15 Python
python读取和保存视频文件
2018/04/16 Python
简单了解Python生成器是什么
2019/07/02 Python
python3实现带多张图片、附件的邮件发送
2019/08/10 Python
利用PyCharm操作Github(仓库新建、更新,代码回滚)
2019/12/18 Python
Python操作Elasticsearch处理timeout超时
2020/07/17 Python
CSS3自定义滚动条样式 ::webkit-scrollbar的示例代码详解
2020/06/01 HTML / CSS
一些常用的HTML5模式(pattern) 总结
2015/07/14 HTML / CSS
前端实现弹幕效果的方法总结(包含css3和canvas的实现方式)
2018/07/12 HTML / CSS
个人对照检查材料
2014/02/12 职场文书
王老吉广告词
2014/03/20 职场文书
家长写给孩子的评语
2014/04/18 职场文书
班级文化建设标语
2014/06/23 职场文书
学生乘坐校车安全责任书
2015/05/11 职场文书
立秋之描写立秋的作文(五年级)
2019/08/08 职场文书
SQLServer2019 数据库的基本使用之图形化界面操作的实现
2021/04/08 SQL Server