UploadManager.php 8.5 KB
Newer Older
王源's avatar
王源 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Date: 2020/3/30
 * Time: 9:56
 */

declare(strict_types=1);

namespace Meibuyu\Micro\Manager;

use Hyperf\HttpMessage\Upload\UploadedFile;
use Meibuyu\Micro\Exceptions\HttpResponseException;

class UploadManager
{

19
    public static $pathPrefix = '/upload/';
王源's avatar
王源 committed
20 21 22 23
    public static $options = [
        'path' => 'default', // 默认保存路径
        'maxSize' => 100000000, // 文件大小
        'temp' => false, // 是否为临时文件
24
        'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg', 'txt', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'rar', 'zip', 'csv'], // 允许上传的文件类型
王源's avatar
王源 committed
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
    ];

    /**
     * 图片上传方法
     * @param $image
     * @param array $options
     * @return string
     * @throws HttpResponseException
     */
    public static function uploadImage($image, $options = [])
    {
        $imgOptions = [
            'path' => 'images',
            'mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']
        ];
        $options = array_merge($imgOptions, $options);
        return self::uploadFile($image, $options);
    }

    /**
     * 表格上传方法
     * @param $excel
     * @param array $options
     * @return string
     * @throws HttpResponseException
     */
    public static function uploadExcel($excel, $options = [])
    {
        $excelOptions = [
            'path' => 'excel',
            'mime' => ['xlsx', 'xls']
        ];
        $options = array_merge($excelOptions, $options);
        return self::uploadFile($excel, $options);
    }

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    /**
     * 表格上传方法获取真实地址
     * @param $excel
     * @param array $options
     * @return string
     * @throws HttpResponseException
     */
    public static function uploadExcelGetRealPath($excel, $options = [])
    {
        $excelOptions = [
            'path' => 'excel',
            'mime' => ['xlsx', 'xls']
        ];
        $options = array_merge($excelOptions, $options);
        return self::uploadFile($excel, $options, true);
    }

王源's avatar
王源 committed
78 79 80 81
    /**
     * 文件上传方法
     * @param UploadedFile $file 上传的文件
     * @param array $options 配置参数
82
     * @param bool $realPath
王源's avatar
王源 committed
83 84 85
     * @return string
     * @throws HttpResponseException
     */
86
    public static function uploadFile($file, $options = [], $realPath = false)
王源's avatar
王源 committed
87
    {
88 89 90 91
        $documentRoot = config('server.settings.document_root');
        if (!$documentRoot) {
            throw new \RuntimeException('未配置静态资源');
        }
王源's avatar
王源 committed
92 93
        $options = self::parseOptions($options);
        if ($file->isValid()) {
94
            $extension = strtolower($file->getExtension());
王源's avatar
王源 committed
95
            // 通过扩展名判断类型
96
            if (!in_array($extension, $options['mime'])) {
王源's avatar
王源 committed
97 98 99 100
                throw new HttpResponseException('文件类型不支持,目前只支持' . implode(',', $options['mime']));
            }
            // 判断文件大小
            if ($file->getSize() > $options['maxSize']) {
101
                throw new HttpResponseException('文件超出系统规定的大小,最大不能超过' . num_2_file_size($options['maxSize']));
王源's avatar
王源 committed
102 103 104
            }
            // 文件重命名,由当前日期时间 + 唯一ID + 扩展名
            $fileName = date('YmdHis') . uniqid() . '.' . $extension;
105
            $savePath = self::parsePath($options, $documentRoot) . $fileName;
王源's avatar
王源 committed
106 107
            $file->moveTo($savePath);
            if ($file->isMoved()) {
108 109 110 111 112
                if ($realPath) {
                    return $savePath;
                } else {
                    return str_replace($documentRoot, '', $savePath);
                }
王源's avatar
王源 committed
113 114 115 116 117
            } else {
                throw new HttpResponseException('文件保存失败');
            }
        } else {
            throw new HttpResponseException('文件无效');
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        }
    }

    /**
     * 文件上传方法(micro-api-flow)
     * @param UploadedFile $file 上传的文件
     * @param array $options 配置参数
     * @param bool $realPath
     * @return string
     * @throws HttpResponseException
     */
    public static function uploadFileGetName($file, $options = [], $realPath = false)
    {
        $documentRoot = config('server.settings.document_root');
        if (!$documentRoot) {
            throw new \RuntimeException('未配置静态资源');
        }
        $options = self::parseOptions($options);
        if ($file->isValid()) {
            $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']));
            }
            // 文件重命名,由当前日期时间 + 唯一ID + 扩展名
            $fileName = date('YmdHis') . uniqid() . '.' . $extension;
            $name = $file->toArray()['name'];
149
            $savePath = self::parsePath($options, $documentRoot) . $fileName;
150 151 152
            $file->moveTo($savePath);
            if ($file->isMoved()) {
                if ($realPath) {
153
                    return $savePath.'?'.$name;
154
                } else {
155
                    return str_replace($documentRoot, '', $savePath.'?'.$name);
156 157 158 159 160 161
                }
            } else {
                throw new HttpResponseException('文件保存失败');
            }
        } else {
            throw new HttpResponseException('文件无效');
王源's avatar
王源 committed
162 163 164
        }
    }

165 166 167 168 169 170
    /**
     * 生成头像
     * @return string|string[]
     */
    public static function createAvatar()
    {
171 172 173 174
        $documentRoot = config('server.settings.document_root');
        if (!$documentRoot) {
            throw new \RuntimeException('未配置静态资源');
        }
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        $img = imagecreatetruecolor(180, 180);
        $bgColor = imagecolorallocate($img, 240, 240, 240);
        imagefill($img, 0, 0, $bgColor);
        $color = imagecolorallocate($img, rand(90, 230), rand(90, 230), rand(90, 230));

        for ($i = 0; $i < 90; $i++) {
            for ($y = 0; $y < 180; $y++) {
                $ad = rand(10, 50); //随机
                if ($ad % 3 == 0) {
                    for ($xx = $i; $xx < $i + 15; $xx++) {
                        for ($yy = $y; $yy < $y + 30; $yy++) {
                            imagesetpixel($img, $xx, $yy, $color);
                        }
                    }
                    $is = ((90 - $i) + 90) - 15; //计算偏移
                    for ($xx = $is; $xx < $is + 15; $xx++) {
                        for ($yy = $y; $yy < $y + 30; $yy++) {
                            imagesetpixel($img, $xx, $yy, $color);
                        }
                    }
                }
                $y += 14;
            }
            $i += 14;
        }

201
        $path = $documentRoot . self::$pathPrefix . 'avatar/default/';
202 203 204 205 206 207
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $fileName = $path . date('YmdHis') . uniqid() . '.png';
        imagepng($img, $fileName);
        imagedestroy($img);//释放内存
208
        return str_replace($documentRoot, '', $fileName);
209 210
    }

王源's avatar
王源 committed
211 212 213
    /**
     * 处理保存路径
     * @param $options
214
     * @param $documentRoot
王源's avatar
王源 committed
215 216
     * @return string
     */
217
    public static function parsePath($options, $documentRoot)
王源's avatar
王源 committed
218
    {
219 220
        if (isset($options['temp']) && $options['temp']) {
            // 如果是临时文件,修改保存路径为临时路径
王源's avatar
王源 committed
221 222
            $options['path'] = 'temp';
        }
223
        $path = $documentRoot . self::$pathPrefix . $options['path'] . '/' . date('Y-m-d');
王源's avatar
王源 committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        if (!is_dir($path)) {
            // 判断路径是否存在,不存在,则创建
            mkdir($path, 0777, true);
        }
        return $path . '/';
    }

    /**
     * 处理配置参数
     * @param array $options
     * @return array
     */
    public static function parseOptions($options = [])
    {
        if ($options == []) {
            return self::$options;
        } else {
            return array_merge(self::$options, $options);
        }
    }

245 246
    public static function deleteFile($path)
    {
247 248 249 250
        $documentRoot = config('server.settings.document_root');
        if (!$documentRoot) {
            throw new \RuntimeException('未配置静态资源');
        }
251
        $path = str_replace(config('app_domain'), '', $path);
252
        $path = $documentRoot . $path;
253 254 255 256 257
        if (file_exists($path)) {
            unlink($path);
        }
    }

258
}