UploadOssService.php 5.42 KB
Newer Older
chentianyu's avatar
chentianyu committed
1 2
<?php

chentianyu's avatar
chentianyu committed
3
namespace Meibuyu\Common\UploadOss;
chentianyu's avatar
chentianyu committed
4 5

use Hyperf\Contract\ConfigInterface;
chentianyu's avatar
chentianyu committed
6
use League\Flysystem\Filesystem;
chentianyu's avatar
chentianyu committed
7 8 9
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpMessage\Upload\UploadedFile;
use League\Flysystem\FileExistsException;
chentianyu's avatar
chentianyu committed
10
use Meibuyu\Common\Exceptions\HttpResponseException;
chentianyu's avatar
chentianyu committed
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
use Psr\Container\ContainerInterface;

class UploadOssService
{

    /**
     * @var FilesystemFactory
     */
    private $factory;

    /**
     * @var ConfigInterface
     */
    private $config;

    /**
     * @var string
     */
    private $urlPrefix;

    /**
     * @var string
     */
    private $appDev;

chentianyu's avatar
chentianyu committed
36 37 38 39 40
    /**
     * @var string
     */
    private $appName;

chentianyu's avatar
chentianyu committed
41 42 43 44 45 46 47 48 49 50
    public static $options = [
        'maxSize' => 10 * 1024 * 1024, // 文件大小,10M
        'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg', 'txt', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'rar', 'zip', 'csv'], // 允许上传的文件类型
    ];

    public function __construct(ContainerInterface $container)
    {
        $this->config = $container->get(ConfigInterface::class);
        $this->factory = $container->get(FilesystemFactory::class);
        $ossConfig = $this->config->get('file.storage.oss');
chentianyu's avatar
chentianyu committed
51
        $this->urlPrefix = 'https://' . $ossConfig['bucket'] . '.' . $ossConfig['endpoint'] . '/';
chentianyu's avatar
chentianyu committed
52
        $this->appDev = $this->config->get('app_env');
chentianyu's avatar
chentianyu committed
53
        $this->appName = $this->config->get('app_name');
chentianyu's avatar
chentianyu committed
54 55 56
    }

    /**
chentianyu's avatar
chentianyu committed
57
     * 上传图片
chentianyu's avatar
chentianyu committed
58
     * @param \Hyperf\HttpMessage\Upload\UploadedFile $image
chentianyu's avatar
chentianyu committed
59
     * @param string $module
chentianyu's avatar
chentianyu committed
60
     * @return array
chentianyu's avatar
chentianyu committed
61
     * @throws \Meibuyu\Common\Exceptions\HttpResponseException
chentianyu's avatar
chentianyu committed
62
     * @author chentianyu
chentianyu's avatar
chentianyu committed
63
     */
chentianyu's avatar
chentianyu committed
64
    public function uploadImage(UploadedFile $image, string $module, int $userId, bool $uniqueFileName = false)
chentianyu's avatar
chentianyu committed
65
    {
chentianyu's avatar
chentianyu committed
66 67 68
        $ext = $image->getExtension();
        $clientFilename = $image->getClientFilename();
        $fileName = $uniqueFileName ? ($this->genUniqueFileName() . '.' . $ext) : $clientFilename;
chentianyu's avatar
chentianyu committed
69
        $options = ['mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']];
chentianyu's avatar
chentianyu committed
70
        $filePath = 'oss2/' . $this->appDev . "/" . $this->appName . "/$module/images/" . today() . "/$userId/" . $clientFilename;
chentianyu's avatar
chentianyu committed
71
        $this->upload($image, $filePath, $options);
chentianyu's avatar
chentianyu committed
72
        $model = new FileModel();
chentianyu's avatar
chentianyu committed
73
        $model = $model->newInstance([
chentianyu's avatar
chentianyu committed
74
            'type'  => 'image',
chentianyu's avatar
chentianyu committed
75
            'module'  => $module,
chentianyu's avatar
chentianyu committed
76
            'user_id' => $userId,
chentianyu's avatar
chentianyu committed
77 78
            'source_name' => $clientFilename,
            'name' => $fileName,
chentianyu's avatar
chentianyu committed
79
            'path' => $this->urlPrefix . $filePath,
chentianyu's avatar
chentianyu committed
80 81
            'ext'  => $ext,
            'size' => num_2_file_size($image->getSize()),
chentianyu's avatar
chentianyu committed
82 83 84 85 86
        ]);
        $model->save();
        return $model->toArray();
    }

chentianyu's avatar
chentianyu committed
87 88 89
    /**
     * 上传文件
     * @param \Hyperf\HttpMessage\Upload\UploadedFile $image
chentianyu's avatar
chentianyu committed
90
     * @param string $module
chentianyu's avatar
chentianyu committed
91
     * @return array
chentianyu's avatar
chentianyu committed
92
     * @throws \Meibuyu\Common\Exceptions\HttpResponseException
chentianyu's avatar
chentianyu committed
93
     * @author chentianyu
chentianyu's avatar
chentianyu committed
94
     */
chentianyu's avatar
chentianyu committed
95
    public function uploadFile(UploadedFile $file, string $module, string $userId, bool $uniqueFileName = false, array $options = [])
chentianyu's avatar
chentianyu committed
96
    {
chentianyu's avatar
chentianyu committed
97 98 99
        $ext = $file->getExtension();
        $clientFilename = $file->getClientFilename();
        $fileName = $uniqueFileName ? ($this->genUniqueFileName() . '.' . $ext) : $clientFilename;
chentianyu's avatar
chentianyu committed
100
        $filePath = 'oss2/' . $this->appDev . "/" . $this->appName . "/$module/files/" . today() . "/$userId/" . $clientFilename;
chentianyu's avatar
chentianyu committed
101 102 103 104
        $this->upload($file, $filePath, $options);
        $model = new FileModel();
        $model = $model->newInstance([
            'type'  => 'file',
chentianyu's avatar
chentianyu committed
105
            'module'  => $module,
chentianyu's avatar
chentianyu committed
106
            'user_id' => $userId,
chentianyu's avatar
chentianyu committed
107 108
            'source_name' => $clientFilename,
            'name' => $fileName,
chentianyu's avatar
chentianyu committed
109
            'path' => $this->urlPrefix . $filePath,
chentianyu's avatar
chentianyu committed
110 111
            'ext'  => $ext,
            'size' => num_2_file_size($file->getSize()),
chentianyu's avatar
chentianyu committed
112 113 114 115 116
        ]);
        $model->save();
        return $model->toArray();
    }

chentianyu's avatar
chentianyu committed
117 118
    /**
     * @param \Hyperf\HttpMessage\Upload\UploadedFile $file
chentianyu's avatar
chentianyu committed
119
     * @param $filePath
chentianyu's avatar
chentianyu committed
120 121
     * @param array $options
     * @return bool
chentianyu's avatar
chentianyu committed
122
     * @throws \Meibuyu\Common\Exceptions\HttpResponseException
chentianyu's avatar
chentianyu committed
123
     * @author chentianyu
chentianyu's avatar
chentianyu committed
124
     */
chentianyu's avatar
chentianyu committed
125
    public function upload(UploadedFile $file, string $filePath, array $options = [])
chentianyu's avatar
chentianyu committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    {
        if ($file->isValid()) {
            $options = array_merge(self::$options, $options);
            $extension = strtolower($file->getExtension());
            // 通过扩展名判断类型
            if (!in_array($extension, $options['mime'])) {
                throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime']));
            }
            // 判断文件大小
            if ($file->getSize() > $options['maxSize']) {
                throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize']));
            }
            try {
                $oss = $this->factory->get('oss');
                $stream = fopen($file->getRealPath(), 'r+');
chentianyu's avatar
chentianyu committed
141
                $res = $oss->writeStream($filePath, $stream);
chentianyu's avatar
chentianyu committed
142 143 144 145 146 147 148 149 150 151
                is_resource($stream) && fclose($stream);
                return $res;
            } catch (FileExistsException $e) {
                throw new HttpResponseException($e->getMessage());
            }
        } else {
            throw new HttpResponseException('文件无效');
        }
    }

chentianyu's avatar
chentianyu committed
152 153 154 155 156 157 158 159 160 161
    /**
     * 生成唯一文件名
     * @return string
     * @author chentianyu
     */
    public function genUniqueFileName()
    {
        return date('YmdHis') . uniqid();
    }

chentianyu's avatar
chentianyu committed
162
}