thinkphp 七牛存储单文件、多文件上传,简化配置

jerry thinkphp 2015年11月19日 收藏
简化使用七牛云存储实现文件上传功能
  1. <?php

  2. /**
  3.  * 上传七牛
  4.  *
  5.  * @author huqitao <huqitaoit@gmail.com>
  6.  */

  7. namespace Common\Utility;

  8. class UploadImg {

  9.     protected $config;
  10.     protected $domain;
  11.     protected $bucket;

  12.     public function __construct($domain, $bucket) {
  13.         $this->domain = $domain;
  14.         $this->bucket = $bucket;
  15.         $this->config = array(
  16.             'maxSize' => 2 * 1024 * 1024, //文件大小
  17.             'rootPath' => './',
  18.             'saveName' => array('uniqid', ''),
  19.             'driver' => 'Qiniu',
  20.             'driverConfig' => array(
  21.                 'secretKey' => '######',  //七牛空间配置参数
  22.                 'accessKey' => '########',
  23.                 'domain' => $this->domain, //空间地址
  24.                 'bucket' => $this->bucket, //空间名称
  25.             )
  26.         );
  27.     }

  28.   

  29.     /**
  30.      * 上传一个文件
  31.      * @param array $file 文件参数
  32.      * @return array 返回 code 与文件路径或错误信息
  33.      */
  34.     public function uploadOne($file) {
  35.         $upload = new \Think\Upload($this->config);
  36.         $info = $upload->uploadOne($file);
  37.         if (!$info) {
  38.             return [550, $upload->getError()];
  39.         }
  40.         return [200, $info['url']]; 
  41.     }
  42.     /**
  43.      * 上传多图
  44.      * @param type $files
  45.      * @return array 返回 code 与文件路径数组 或错误信息
  46.      */
  47.     public function uploads($files) {
  48.         $upload = new \Think\Upload($this->config);
  49.         $info = $upload->upload($files);
  50.         if (!$info) {
  51.             return [550, $upload->getError()];
  52.         }
  53.         foreach ($info as $v) {
  54.             $pArray[] = "http://".$this->domain."/".strtr($v['name'], '/', '_');
  55.         }
  56.         return [200, $pArray];
  57.     }

  58. }
使用方法,单图上传:
  1. public function uploadSchool() {
  2.         if (IS_POST) {
  3.             $domain = "#####";
  4.             $bucket = "###";
  5.             if (empty($_FILES)) {
  6.                 $this->ajaxReturn(makeinformation(550, "没有上传图片"));
  7.             }
  8.             $uploadImg = new \Common\Utility\UploadImg($domain, $bucket);
  9.             $data = $uploadImg->uploadOne($_FILES['file']);
  10.             if ($data[0] != 200) {
  11.                 $this->ajaxReturn(makeinformation(550, $data[1]));//失败返回错误
  12.             }
  13.             $this->ajaxReturn(makeinformation(200, '', array('url' => $data[1]))); //成功返回图片绝对地址
  14.         }
  15.     }