dd

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

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

/**
 * 上传七牛
 *
 * @author huqitao <huqitaoit@gmail.com>
 */

namespace Common\Utility;

class UploadImg {

    protected $config;
    protected $domain;
    protected $bucket;

    public function __construct($domain, $bucket) {
        $this->domain = $domain;
        $this->bucket = $bucket;
        $this->config = array(
            'maxSize' => 2 * 1024 * 1024, //文件大小
            'rootPath' => './',
            'saveName' => array('uniqid', ''),
            'driver' => 'Qiniu',
            'driverConfig' => array(
                'secretKey' => '######',  //七牛空间配置参数
                'accessKey' => '########',
                'domain' => $this->domain, //空间地址
                'bucket' => $this->bucket, //空间名称
            )
        );
    }

  

    /**
     * 上传一个文件
     * @param array $file 文件参数
     * @return array 返回 code 与文件路径或错误信息
     */
    public function uploadOne($file) {
        $upload = new \Think\Upload($this->config);
        $info = $upload->uploadOne($file);
        if (!$info) {
            return [550, $upload->getError()];
        }
        return [200, $info['url']]; 
    }
    /**
     * 上传多图
     * @param type $files
     * @return array 返回 code 与文件路径数组 或错误信息
     */
    public function uploads($files) {
        $upload = new \Think\Upload($this->config);
        $info = $upload->upload($files);
        if (!$info) {
            return [550, $upload->getError()];
        }
        foreach ($info as $v) {
            $pArray[] = "http://".$this->domain."/".strtr($v['name'], '/', '_');
        }
        return [200, $pArray];
    }

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