-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathCloudStorageAliyun.php
More file actions
100 lines (81 loc) · 3.18 KB
/
CloudStorageAliyun.php
File metadata and controls
100 lines (81 loc) · 3.18 KB
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
91
92
93
94
95
96
97
98
99
100
<?php
require_once ROOT_DIR . '/nonfree/class/AliyunOss.phar';
use OSS\OssClient;
/**
* 阿里云OSS云存储
*
* 实现阿里云OSS云存储的文件上传、下载、服务器端签名
*/
class CloudStorageAliyun extends CloudStorageBase {
public function upload($localFile, $remoteFile, $allowOverwrite = false, $fileName = null) {
$ossClient = new OssClient(CLOUD_STORAGE_AK, CLOUD_STORAGE_SK, CLOUD_STORAGE_ENDPOINT);
if (!$allowOverwrite && $ossClient->doesObjectExist(CLOUD_STORAGE_BUCKET, $remoteFile)) {
return;
}
$options = [
OssClient::OSS_HEADERS => [],
];
$headers = &$options[OssClient::OSS_HEADERS];
$fileName = rawurlencode(str::basename(trim($fileName)));
if ($fileName !== '' && !self::noAttrname($fileName)) {
$headers[OssClient::OSS_CONTENT_DISPOSTION] = "attachment; filename=\"$fileName\"; filename*=utf-8''$fileName";
}
$ossClient->uploadFile(CLOUD_STORAGE_BUCKET, $remoteFile, $localFile, $options);
}
private static function gmt_iso8601($time) {
return str_replace('+00:00', '.000Z', gmdate('c', $time));
}
public function getUploadForm($key, $fileName, $fileSize, $fileMd5 = null) {
$ossClient = new OssClient(CLOUD_STORAGE_AK, CLOUD_STORAGE_SK, CLOUD_STORAGE_ENDPOINT);
if ($ossClient->doesObjectExist(CLOUD_STORAGE_BUCKET, $key)) {
return [
'fileExists' => true,
];
}
// 上传条件
$conditions = [];
// 指定文件大小
$fileSize = (int)$fileSize;
$conditions[] = ['content-length-range', $fileSize, $fileSize];
// 指定key
$conditions[] = ['eq', '$key', $key];
// 指定文件md5
if ($fileMd5 !== null) {
$fileMd5 = base64_encode(hex2bin(trim($fileMd5)));
$conditions[] = ['eq', '$Content-MD5', $fileMd5];
}
// 超时时间:1小时
$expire = 3600;
$end = time() + $expire;
$expiration = self::gmt_iso8601($end);
// 上传策略
$policy = base64_encode(json_encode([
'expiration' => $expiration,
'conditions' => $conditions
]));
// 签名
$signature = base64_encode(hash_hmac('sha1', $policy, CLOUD_STORAGE_SK, true));
// 上传表单模板
$data = [
'fileExists' => false,
'requestUrl' => CLOUD_STORAGE_CLIENT_ENDPOINT,
'method' => 'POST',
'enctype' => 'multipart/form-data',
'formData' => [
'OSSAccessKeyId' => CLOUD_STORAGE_AK,
'policy' => $policy,
'signature' => $signature,
'key' => $key,
],
'fileFieldName' => 'file',
];
$fileName = rawurlencode(str::basename(trim($fileName)));
if ($fileName !== '' && !self::noAttrname($fileName)) {
$data['formData']['Content-Disposition'] = "attachment; filename=\"$fileName\"; filename*=utf-8''$fileName";
}
if ($fileMd5 !== null) {
$data['formData']['Content-MD5'] = $fileMd5;
}
return $data;
}
}