用于ThinkPHP 3.2的阿里云OSS驱动

By | 2014年12月9日

看过网上的一些例子都过于复杂,包含了官方的phpsdk那一大坨东西,理论上我只需要简单的上传文件而已,不需要那么多东西,于是自己写了一下。

以下代码保存到/yourpath/ThinkPHP/Library/Think/Upload/Driver/Oss.class.php即可

<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 废墟 <r.anerg@gmail.com> <http://anerg.com>
// +----------------------------------------------------------------------

namespace Think\Upload\Driver;

class Oss {

    const OSS_HOST = 'oss.aliyuncs.com';

    /**
     * 上传文件根目录
     * @var string
     */
    private $rootPath;

    /**
     * 上传错误信息
     * @var string
     */
    private $error  = '';
    private $config = array(
        'access_id'  => '', //阿里云Access Key ID
        'access_key' => '', //阿里云Access Key Secret
        'bucket'     => '', //空间名称
        'timeout'    => 90, //超时时间
    );

    /**
     * 构造函数,用于设置上传根路径
     * @param array  $config FTP配置
     */
    public function __construct($config) {
        /* 默认FTP配置 */
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 检测上传根目录(阿里云上传时支持自动创建目录,直接返回)
     * @param string $rootpath   根目录
     * @return boolean true-检测通过,false-检测失败
     */
    public function checkRootPath($rootpath) {
        /* 设置根目录 */
        $this->rootPath = trim($rootpath, './') . '/';
        return true;
    }

    /**
     * 检测上传目录(阿里云上传时支持自动创建目录,直接返回)
     * @param  string $savepath 上传目录
     * @return boolean          检测结果,true-通过,false-失败
     */
    public function checkSavePath($savepath) {
        return true;
    }

    /**
     * 创建文件夹 (阿里云上传时支持自动创建目录,直接返回)
     * @param  string $savepath 目录名称
     * @return boolean          true-创建成功,false-创建失败
     */
    public function mkdir($savepath) {
        return true;
    }

    /**
     * 保存指定文件
     * @param  array   $file    保存的文件信息
     * @param  boolean $replace 同名文件是否覆盖
     * @return boolean          保存状态,true-成功,false-失败
     */
    public function save($file, $replace = true) {
        $_headers = array('Content-Type: ' . $file['type']);
        $resource = fopen($file['tmp_name'], 'r');

        $path = $this->rootPath . $file['savepath'] . $file['savename'];

        $uri = "/{$this->config['bucket']}{$path}";
        $ch  = curl_init('http://' . self::OSS_HOST . $uri);

        $date = gmdate('D, d M Y H:i:s \G\M\T');

        array_push($_headers, "Date: {$date}");

        $sign_string = "PUT\n\n" . $file['type'] . "\n" . $date . "\n" . $uri;
        $sign        = $this->hex_to_base64(hash_hmac('sha1', $sign_string, $this->config['access_key']));

        array_push($_headers, 'Authorization: OSS ' . $this->config['access_id'] . ':' . $sign);

        fseek($resource, 0, SEEK_END);
        $length = ftell($resource);
        fseek($resource, 0);

        array_push($_headers, "Content-Length: {$length}");

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_INFILE, $resource);
        curl_setopt($ch, CURLOPT_INFILESIZE, $length);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $_headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->config['timeout']);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $response = curl_exec($ch);
        $status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        fclose($resource);
        if ($status == 200) {
            return true;
        } else {
            $this->error = $response;
            return false;
        }
    }

    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError() {
        return $this->error;
    }


    private function hex_to_base64($str) {
        $result = '';

        for ($i = 0; $i < strlen($str); $i += 2) {
            $result .= chr(hexdec(substr($str, $i, 2)));
        }

        return base64_encode($result);
    }

}

使用方法也比较简单,如果只有一个bucket则可以把配置写入config.php里,内容如下

'FILE_UPLOAD_TYPE' => 'Oss',
'UPLOAD_TYPE_CONFIG' => array(
    'access_id' => 'access_id', //阿里云Access Key ID
    'access_key' => 'access_key', //阿里云Access Key Secret 
    'bucket' => 'bucket' //阿里云的bucket
),

如果你需要将不同的文件存入不同的bucket则需要在上传方法中采用动态配置

$config     = array(
    'maxSize'  => 0,
    'exts'     => array('jpg', 'jpeg', 'png'),
    'saveName' => array('uniq_photo_name', '__FILE__'),
    'rootPath' => '/',
);
$oss_config = array(
    'access_id'  => 'access_id', //阿里云Access Key ID
    'access_key' => 'access_key', //阿里云Access Key Secret 
    'bucket'     => 'bucket'
);
$upload     = new \Think\Upload($config, 'Oss', $oss_config);

这样就不用加载那一大坨恶心的sdk了。。

6 thoughts on “用于ThinkPHP 3.2的阿里云OSS驱动

  1. tgc

    HTTP/1.1 100 Continue

    HTTP/1.1 400 Bad Request
    Date: Fri, 01 May 2015 11:40:18 GMT
    Content-Type: application/xml
    Content-Length: 351
    Connection: close
    Server: AliyunOSS
    x-oss-request-id: 55436622E70121344F6B97A3

    InvalidArgument Authorization header is invalid. OSS :YGaV6wUYNjVRpW9CYxpK3x3DwWw= Authorization 55436622E70121344F6B97A3 oss-cn-hangzhou.aliyuncs.com
    怎么回事

    D 和 key 和 bucket 肯定是没有填写错误
    //上传文件阿里云
    ‘FILE_UPLOAD_TYPE’ => ‘Oss’,
    ‘UPLOAD_TYPE_CONFIG’ => array(
    ‘access_id’ => ‘H1RL9qBtTVDp****’, //阿里云Access Key ID
    ‘access_key’ => ‘dsCLEH09N2Spwnn2qZux7D7yMJ****’, //阿里云Access Key Secret
    ‘bucket’ => ‘zhapposs’ //阿里云的bucket
    ),

    Reply

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据