<?php namespace Meibuyu\Common\UploadOss\Example; use App\Controller\AbstractController; use Hyperf\HttpMessage\Upload\UploadedFile; use Meibuyu\Common\UploadOss\UploadOssService; use Meibuyu\Micro\Exceptions\HttpResponseException; use Meibuyu\Common\UploadOss\Example\Common\Enum\OssEnum; use Meibuyu\Micro\Model\Auth; /** * @author chentianyu */ class UploadExample extends AbstractController { /** * @Inject * @var UploadOssService */ private $service; /** * 先创建记录上传信息表 oss_files; */ //CREATE TABLE `oss_files` ( //`id` int(11) NOT NULL AUTO_INCREMENT, //`type` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文件类型', //`module` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '模块名', //`source_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '源文件名', //`name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文件名', //`path` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文件路径', //`user_id` varchar(16) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户id', //`ext` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '文件后缀', //`size` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件大小', //`created_at` timestamp NULL DEFAULT NULL, //PRIMARY KEY (`id`) //) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='oss文件表' /** * 上传图片 * @return mixed * @throws HttpResponseException * @throws \Meibuyu\Micro\Exceptions\HttpResponseException * @author chentianyu */ public function image() { $image = $this->request->file('image'); $userId = Auth::id()??0; $module = OssEnum::PRODUCT; if (!$image) { throw new HttpResponseException('请上传图片'); } /** * UploadedFile $image * string $module 模块名称,常量定义在 namespace App\Common\Enum\OssEnum * int $userId * bool $uniqueFileName 是否重新生成唯一文件名(默认否,沿用源文件名,注意文件重复上传会报oss错误。) */ $res = $this->service->uploadImage($image, $module, $userId, $uniqueFileName = false); return success('上传成功', $res); } /** * 上传文件 * @return mixed * @throws HttpResponseException * @throws \Meibuyu\Micro\Exceptions\HttpResponseException * @author chentianyu */ public function file() { $file = $this->request->file('file'); $userId = Auth::id()??0; $module = OssEnum::PRODUCT_CHILD; if (!$file) { throw new HttpResponseException('请上传文件'); } /** * UploadedFile $file * string $module 模块名称,常量定义在 namespace App\Common\Enum\OssEnum * int $userId * bool $uniqueFileName 是否重新生成唯一文件名(默认否,沿用源文件名,注意文件重复上传会报oss错误。) * array $options 其他选项 */ $res = $this->service->uploadFile($file, $module, $userId, $uniqueFileName = false, $options = ['maxSize' => 10 * 1024 * 1024]); return success('上传成功', $res); } }