侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

框架(架构)  /  管理员 发布于 7年前   173

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

1、文章视图中调用Plupload

$model, 'attribute'=>'cover_img', 'url'=>'/file/upload',//处理文件上传控制器])?>

2、\common\widgets\Plupload 组件

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.='
'; $this->_html.=Html::activeLabel($model,$attribute); $this->_html.=Html::activeHiddenInput($model,$attribute,['id'=>'hidden_input','value'=>$path]); $this->_html .= '
'; $this->_html.=' '; 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

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('');     $('#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相关资源

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

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程序设计有所帮助。

您可能感兴趣的文章:

  • 基于ThinkPHP5.0实现图片上传插件
  • thinkphp实现图片上传功能分享
  • ThinkPHP文件上传实例教程
  • ThinkPHP结合AjaxFileUploader实现无刷新文件上传的方法
  • Thinkphp多文件上传实现方法
  • thinkPHP3.2简单实现文件上传的方法
  • 封装ThinkPHP的一个文件上传方法实例
  • thinkphp jquery实现图片上传和预览效果
  • PHP + plupload.js实现多图上传并显示进度条加删除实例代码
  • 使用JS+plupload直接批量上传图片到又拍云
  • thinkPHP5框架整合plupload实现图片批量上传功能的方法


  • 上一条:
    yii2.0实现验证用户名与邮箱功能
    下一条:
    Yii2隐藏frontend/web和backend/web的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客