PHP 上传图片视频至阿里云OSS

发布于:2024-06-15 ⋅ 阅读:(161) ⋅ 点赞:(0)
public function upload(Request $request): Json
    {
        if ($request->isPost()) {

            $param = $request->param();
            $field = $param['file_field'] ?? 'file';
            $dir   = $param['file_dir'] ?? 'uploads';
            // 文件类型,默认图片
            $file_type = $param['file_type'] ?? 'image';

            // 上传到本地,可自行修改为oss之类的
            $config = config('filesystem.disks.aliyun');

            $filess = $request->file();
            try {
                validate([$field => $config['validate'][$file_type]])->check($filess);
            } catch (ValidateException $e) {
                return json([

                    'message' => $e->getMessage()
                ], 500);
            }
            $file = $filess[$field];
            $files  = $_FILES[$field];
            $name   = $files['name'];
            $format = strrchr($name, '.'); //截取文件后缀名如 (.jpg)


            // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
            $accessKeyId = $config['accessId'];
            $accessKeySecret = $config['accessSecret'];
            // Endpoint以北京为例,其它Region请按实际情况填写。
            $endpoint = $config['endpoint'];
            // 设置存储空间名称。
            $bucket = $config['bucket'];
            $object = 'uploads/' . date('Ymd') . '/' . sha1(date('YmdHis', time()) . uniqid()) . $format;
            $filePath = $files['tmp_name'];

            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

                $result = $ossClient->uploadFile($bucket, $object, $filePath);
                if (!$result) {
                    return json(['status' => 1, 'message' => '上传失败']);
                } else {
                    $url = str_replace("http://zitisheji2022.oss-cn-beijing.aliyuncs.com", "https://oss.zitisheji.com", $result['info']['url']);
                    $infos = getimagesize($url);
                    $width = $infos[0];
                    $hight = $infos[1];
                    $ratio = 330 / $width;

                    $imghight = round($hight * $ratio);

                    return json([
                        'code'                 => 200,
                        'initialPreview'       => [$url],
                        'initialPreviewAsData' => true,
                        'showDownload'         => false,
                        'initialPreviewConfig' => [
                            [
                                'downloadUrl' => $url,
                                'key'         => str_replace("\\", '/', $name),
                                'caption'     => str_replace("\\", '/', $name),
                                'url'         => url('admin/file/del', ['file' => $url])->build(),
                                'size'        => $file->getSize(),
                                'high'        => $imghight,
                            ]
                        ]
                    ]);
                }
            } catch (OssException $e) {

                return json([
                    'message' => $e->getMessage()
                ], 500);
            }
        }

        return api_error('非法访问');
    }