PHP Laravel 上传图片、文件等类封装


Posted in PHP onAugust 16, 2017

今天把项目中上传功能封装成类,方便后面使用,简单的封装了一下,感觉还不怎么好,后面继续优化。

具体代码如下:

<?php 
/** 
 * Created by PhpStorm. 
 * User: wady www.bcty365.com 
 * Date: 2017/8/16 
 * Time: 14:52 
 */ 
namespace App\ThinkClass; 
use Symfony\Component\HttpFoundation\File\UploadedFile; 
class UploadClass 
{ 
  /** 
   * @var UploadedFile $file; 
   */ 
  protected $file; 
  /** 
   * 上传错误信息 
   * @var string 
   */ 
  private $error = ''; //上传错误信息 
  private $fullPath='';//绝对地址 
  private $config = array( 
    'maxSize'    => 3*1024*1024, //上传的文件大小限制 (0-不做限制) 
    'exts'     => array('jpg','jpeg','gif','png','doc','docx','xls','xlsx','ppt','pptx','pdf','rar','zip'), //允许上传的文件后缀 
    'subName'    => '', //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组 
    'rootPath'   => '/uploads/', //保存根路径 
    'savePath'   => '', //保存路径 
    'thumb'     => array(),//是裁剪压缩比例 
  ); 
  public function __construct($config = array()){ 
    /* 获取配置 */ 
    $this->config  =  array_merge($this->config, $config); 
    if(!emptyempty($this->config['exts'])){ 
      if (is_string($this->exts)){ 
        $this->config['exts'] = explode(',', $this->exts); 
      } 
      $this->config['exts'] = array_map('strtolower', $this->exts); 
    } 
    $this->config['subName'] = $this->subName ? ltrim($this->subName,'/') : '/'.date('Ymd'); 
    $this->fullPath = rtrim(public_path(),'/').$this->config['rootPath']; 
  } 
  public function __get($name) { 
    return $this->config[$name]; 
  } 
  public function __set($name,$value){ 
    if(isset($this->config[$name])) { 
      $this->config[$name] = $value; 
    } 
  } 
  public function __isset($name){ 
    return isset($this->config[$name]); 
  } 
  /** 
   * 获取最后一次上传错误信息 
   * @return string 错误信息 
   */ 
  public function getError(){ 
    return $this->error; 
  } 
  public function upload($file){ 
     if(emptyempty($file)){ 
       $this->error = '没有上传的文件'; 
       return false; 
     } 
     if(!$this->checkRootPath($this->fullPath)){ 
       $this->error = $this->getError(); 
       return false; 
     } 
     $fileSavePath=$this->fullPath.$this->savePath.$this->subName; 
     if(!$this->checkSavePath($fileSavePath)){ 
       $this->error = $this->getError(); 
       return false; 
     } 
     $files =array(); 
     if(!is_array($file)){ 
       //如果不是数组转成数组 
       $files[]=$file; 
     }else{ 
       $files=$file; 
     } 
    $info  = array(); 
     $imgThumb = new \App\ThinkClass\ThumbClass(); 
     foreach ($files as $key=>$f){ 
       $this->file=$f; 
        $f->ext = strtolower($f->getClientOriginalExtension()); 
       /*文件上传检查*/ 
       if (!$this->check($f)){ 
         continue; 
       } 
       $fileName = str_random(12).'.'.$f->ext; 
       /* 保存文件 并记录保存成功的文件 */ 
       if ($this->file->move($fileSavePath,$fileName)) { 
         /*图片按照宽高比例压缩*/ 
         \Log::notice($fileSavePath.$fileName); 
         if(!emptyempty($this->thumb) && is_array($this->thumb)){ 
           $imgThumb ->thumb($this->thumb,$fileSavePath.'/'.$fileName); 
         } 
         $info[]=$this->rootPath.$this->savePath.$this->subName.'/'.$fileName; 
       } 
     } 
     return is_array($info) ? $info : false; 
  } 
  /** 
   * 检测上传根目录 
   * @param string $rootpath  根目录 
   * @return boolean true-检测通过,false-检测失败 
   */ 
  protected function checkRootPath($rootpath){ 
    if(!(is_dir($rootpath) && is_writable($rootpath))){ 
      $this->error = '上传根目录不存在!'; 
      return false; 
    } 
    return true; 
  } 
  /** 
   * 检测上传目录 
   * @param string $savepath 上传目录 
   * @return boolean     检测结果,true-通过,false-失败 
   */ 
  public function checkSavePath($savepath){ 
    /* 检测并创建目录 */ 
    if (!$this->mkdir($savepath )) { 
      return false; 
    } else { 
      /* 检测目录是否可写 */ 
      if (!is_writable($savepath)) { 
        $this->error = '上传目录不可写!'; 
        return false; 
      } else { 
        return true; 
      } 
    } 
  } 
  /** 
   * 检查上传的文件 
   * @param array $file 文件信息 
   */ 
  private function check($file) { 
    /* 检查文件大小 */ 
    if (!$this->checkSize($file->getSize())) { 
      $this->error = '上传文件大小不符!'; 
      return false; 
    } 
    /* 检查文件后缀 */ 
    if (!$this->checkExt($file->ext)) { 
      $this->error = '上传文件后缀不允许'; 
      return false; 
    } 
    /* 通过检测 */ 
    return true; 
  } 
  /** 
   * 检查文件大小是否合法 
   * @param integer $size 数据 
   */ 
  private function checkSize($size) { 
    return !($size > $this->maxSize) || (0 == $this->maxSize); 
  } 
  /** 
   * 检查上传的文件后缀是否合法 
   * @param string $ext 后缀 
   */ 
  private function checkExt($ext) { 
    return emptyempty($this->config['exts']) ? true : in_array(strtolower($ext), $this->exts); 
  } 
  /** 
   * 创建目录 
   * @param string $savepath 要创建的穆里 
   * @return boolean     创建状态,true-成功,false-失败 
   */ 
  protected function mkdir($savepath){ 
    if(is_dir($savepath)){ 
      return true; 
    } 
    if(mkdir($savepath, 0777, true)){ 
      return true; 
    } else { 
      $this->error = "目录创建失败"; 
      return false; 
    } 
  } 
}

使用案例:

头部引用  use App\ThinkClass\UploadClass; 

$upload = new UploadClass(); 
$upload->exts=array('jpg','png'); 
$upload->maxSize=5*1024*1024; 
$upload->savePath='course/uid_6'; 
$file = $request->file('fileImg'); 
$aa = $upload->upload($file); 
dd($aa);

总结

以上所述是小编给大家介绍的PHP Laravel 上传图片、文件等类封装,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

PHP 相关文章推荐
加速XP搜索功能堪比vista
Mar 22 PHP
浅析PHP 按位与或 (^ 、&amp;)
Jun 21 PHP
php自定义的格式化时间示例代码
Dec 05 PHP
ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼
Mar 25 PHP
PHP中抽象类和抽象方法概念与用法分析
May 24 PHP
Smarty日期时间操作方法示例
Nov 15 PHP
PHP实现的常规正则验证helper公共类完整实例
Apr 27 PHP
Nginx下ThinkPHP5的配置方法详解
Aug 01 PHP
php微信公众号开发之欢迎老朋友
Oct 20 PHP
PHP数组对象与Json转换操作实例分析
Oct 22 PHP
TP5框架使用QueryList采集框架爬小说操作示例
Mar 26 PHP
详细分析PHP 命名空间(namespace)
Jun 30 PHP
PHP数据库操作三:redis用法分析
Aug 16 #PHP
PHP数据库操作二:memcache用法分析
Aug 16 #PHP
PHP数据库编程之MySQL优化策略概述
Aug 16 #PHP
PHP回调函数与匿名函数实例详解
Aug 16 #PHP
搭建自己的PHP MVC框架详解
Aug 16 #PHP
Laravel使用支付宝进行支付的示例代码
Aug 16 #PHP
laravel 中如何使用ajax和vue总结
Aug 16 #PHP
You might like
php is_file()和is_dir()用于遍历目录时用法注意事项
2010/03/02 PHP
PHP中基本符号及使用方法
2010/03/23 PHP
解析yahoo邮件用phpmailer发送的实例
2013/06/24 PHP
PHP 下载文件时如何自动添加bom头及解释BOM头和去掉bom头的方法
2016/01/04 PHP
thinkphp项目部署到Linux服务器上报错“模板不存在”如何解决
2016/04/27 PHP
JavaScript DOM学习第一章 W3C DOM简介
2010/02/19 Javascript
风吟的小型JavaScirpt库 (FY.JS).
2010/03/09 Javascript
基于jquery自定义的漂亮单选按钮RadioButton
2013/11/19 Javascript
jquery选择器需要注意的问题
2014/11/26 Javascript
简述AngularJS的控制器的使用
2015/06/16 Javascript
jquery实现两个图片渐变切换效果的方法
2015/06/25 Javascript
简单解析JavaScript中的__proto__属性
2016/05/10 Javascript
Highcharts 多个Y轴动态刷新数据的实现代码
2016/05/28 Javascript
微信浏览器禁止页面下拉查看网址实例详解
2017/06/28 Javascript
Vue.js计算机属性computed和methods方法详解
2019/10/12 Javascript
详解ECMAScript2019/ES10新属性
2019/12/06 Javascript
[03:27]最受玩家喜爱奖提名:PZH_Element 致玩家寄语
2016/12/20 DOTA
[56:29]Secret vs Optic 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
python操作sqlite的CRUD实例分析
2015/05/08 Python
python爬虫神器Pyppeteer入门及使用
2019/07/13 Python
python利用wx实现界面按钮和按钮监听和字体改变的方法
2019/07/17 Python
Python 下载及安装详细步骤
2019/11/04 Python
Python+PyQt5实现灭霸响指功能
2020/05/25 Python
详解Django ORM引发的数据库N+1性能问题
2020/10/12 Python
使用Canvas操作像素的方法
2018/06/14 HTML / CSS
.NET面试题:什么是反射
2016/09/30 面试题
Ajxa常见问题都有哪些
2014/03/26 面试题
Servlet如何得到服务器的信息
2015/12/22 面试题
小学教师的自我评价范例
2013/10/31 职场文书
服务中心夜班服务员岗位职责
2013/11/27 职场文书
高中美术教学反思
2014/01/19 职场文书
爱之链教学反思
2014/04/30 职场文书
2015年六一儿童节活动总结
2015/02/11 职场文书
2015年施工员工作总结范文
2015/04/20 职场文书
迎新年主持词
2015/07/06 职场文书
MySQL 原理与优化之Update 优化
2022/08/14 MySQL