-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileClient.php
89 lines (84 loc) · 2.5 KB
/
FileClient.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
<?php
/**
* 文件服务client
*/
namespace Wanshi\FileClient;
use GuzzleHttp\Client;
class FileClient{
private $appid;
private $appsecret;
private $time;
public function __construct($appid, $appsecret, $domain){
$this->time = time();
$this->appid = $appid;
$this->appsecret= $appsecret;
$this->domain = trim($domain, '/');
$this->client = new Client([
'base_uri' => $this->domain,
'timeout' => 20,
'exceptions' => false,
]);
}
/*
* 上传
*/
public function create($file){
return $this->request('/file', 'POST', [
'multipart' => [
[
'name' => 'sign',
'contents' => $this->sign('/file', 'POST', ['file'=>$file])
],
[
'name' => 'file',
'contents' => fopen($file, 'r')
]
]
]);
}
/**
* 删除文件
*/
public function delete($ids){
$url = '/file';
return $this->request($url, 'DELETE', [
'form_params' => [
'ids' => $ids,
'sign' => $this->sign($url, 'DELETE', ['ids' => $ids])
]
]);
}
//获取文件链接
public function url($id, $data=[]){
$url = '/file/' . $id;
$sign = $this->sign($url, 'GET', $data);
$data['sign'] = $sign;
return $this->domain . $url . '?' . http_build_query($data);
}
//签名
private function sign($path, $method='GET', $data = []){
$dataStr = '';
if(!empty($data)){
ksort($data);
foreach($data as $k=>$v){
//文件
if(is_file($v)){
$v = md5_file($v);
}
$dataStr .= sprintf('[%s:%s]', $k, $v);
}
}
return $this->appid . '-' . md5(trim($path, '/') . strtoupper($method) . $dataStr . $this->appsecret . $this->time) . '-' . $this->time;
}
private function request($path, $method, $data){
$method = strtoupper($method);
$response = $this->client->request($method, $path, $data);
$status = $response->getStatusCode();
$body = $response->getBody()->getContents();
if ( ($status >= 200 && $status < 300)|| ($status == 304) ) {
return [true, $body];
} else {
return [false, $body];
}
}
}