-
Notifications
You must be signed in to change notification settings - Fork 4
/
AliyunOss.php
90 lines (85 loc) · 2.55 KB
/
AliyunOss.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace aliyun\oss;
use yii\base\Component;
use OSS\Core\OssException;
require_once __DIR__.'/aliyun-oss-php-sdk-2.2.2/autoload.php';
/**
*
* @author weijian
* 'oss'=>[
* 'class'=>'aliyun\oss\AliyunOss',
* 'bucket'=>'',
* 'prefix'=>'',
* 'AccessKeyId' => '',
* 'AccessKeySecret' => '',
* 'endpoint'=>'oss-cn-hangzhou.aliyuncs.com',
* 'imageHost' => 'http://bucket.img-cn-hangzhou.aliyuncs.com/'
* ],
*/
class AliyunOss extends Component
{
public $bucket = '';
public $prefix = ''; //路径前缀
public $AccessKeyId = '';
public $AccessKeySecret = '';
public $endpoint = 'oss-cn-hangzhou.aliyuncs.com';
public $imageHost = 'http://bucket.img-cn-hangzhou.aliyuncs.com/';
private $client;
public function init()
{
if (empty($this->imageHost)) {
$this->imageHost = 'http://'.$this->bucket.'/'.$this->endpoint.'/';
}
try {
$this->client = new \OSS\OssClient($this->AccessKeyId, $this->AccessKeySecret, $this->endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
}
/**
* 上传文件到OSS
*/
public function upload2oss($tempName, $path=null)
{
try {
$stream = file_get_contents($tempName);
if (empty($path)){
$path = date('Ymd').mb_substr(md5($stream), -8);
}
$this->client->putObject($this->bucket, $this->prefix.$path, $stream);
return $path;
} catch (OssException $ex) {
throw new \ErrorException( "Error: " . $ex->getMessage() . "\n");
}
}
/**
* 上传文件流到OSS
*/
public function uploadStream2oss($stream,$filename)
{
try {
return $this->client->putObject( $this->bucket, $this->prefix.$filename, $stream);
} catch (OSSException $ex) {
throw new \ErrorException( "Error: " . $ex->getMessage() . "\n");
}
}
/**
* 获取图片地址
* @param string $path 路径
* @param string $style 样式
*/
public function getImageUrl($path, $style=null)
{
if (empty($style)){
return $this->imageHost.$this->prefix.$path;
}
return $this->imageHost.$this->prefix.$path.'@!'.$style;
}
public function __call($method_name, $args)
{
if(empty($args['Bucket'])){
$args['Bucket'] = $this->bucket;
}
return call_user_func_array([$this->client, $method_name],$args);
}
}