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
<?php
 
namespace app\common\library\storage\engine;
 
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Filesystem;
 
/**
 * 阿里云存储引擎 (OSS)
 */
class Aliyun extends Server
{
    private $config;
 
    /**
     * 构造方法
     */
    public function __construct($config)
    {
        parent::__construct();
        $this->config = $config;
    }
 
    /**
     * 执行上传
     */
    public function upload()
    {
        try {
            // 扩展名
            $ext = $this->getOriginalExtension();
            $saveName = date('Ymd').'/'.md5((string) microtime(true)).".{$ext}";
            //$saveName = Filesystem::disk('public')->putFile( '', $this->file);
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            // 创建目录
            $ossClient->createObjectDir($this->config['bucket'], date('Ymd'));
            // 上传文件
            $ossClient->uploadFile(
                $this->config['bucket'],
                $saveName,
                $this->getRealPath()
            );
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return $saveName;
    }
 
    /**
     * 删除文件
     */
    public function delete($fileName)
    {
        try {
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $ossClient->deleteObject($this->config['bucket'], $fileName);
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }
 
    /**
     * 返回文件路径
     */
    public function getFileName()
    {
        return $this->fileName;
    }
 
}