Commit 411a5b57 authored by chentianyu's avatar chentianyu

oss

parent 50ef9161
<?php
namespace Meibuyu\Common\Example\Common;
/**
* @author chentianyu
*/
class OssEnum
{
const PRODUCT = 'product';
const PRODUCT_CHILD = 'product-child';
}
\ No newline at end of file
<?php
namespace Meibuyu\Common\Example;
use App\Controller\AbstractController;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Meibuyu\Common\UploadOss\UploadOssService;
use Meibuyu\Micro\Exceptions\HttpResponseException;
use Meibuyu\Common\Example\Common\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 是否为唯一文件名,默认否
*/
$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()
{
$image = $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 是否为唯一文件名,默认否
* array $options 其他选项
*/
$res = $this->service->uploadFile($file, $module, $userId, $uniqueFileName = false, $options = ['maxSize' => 10 * 1024 * 1024]);
return success('上传成功', $res);
}
}
\ No newline at end of file
...@@ -7,23 +7,31 @@ namespace Meibuyu\Common\UploadOss; ...@@ -7,23 +7,31 @@ namespace Meibuyu\Common\UploadOss;
use Hyperf\DbConnection\Model\Model; use Hyperf\DbConnection\Model\Model;
/** /**
* 模型类 File * oss模型类 OssFiles
* @package App\Model * @package App\Model
* @property integer $id * @property integer $id
* @property string $type 文件类型 * @property string $type 文件类型
* @property string $module 模块 * @property string $module 模块名
* @property string $source_name 源文件名
* @property string $name 文件名 * @property string $name 文件名
* @property string $path 文件路径 * @property string $path 文件路径
* @property string $ext 文件后缀
* @property string $user_id 用户id * @property string $user_id 用户id
* @property string $ext 文件后缀
* @property string $size 文件大小 * @property string $size 文件大小
* @property string $created_at * @property string $created_at
*/ */
class FileModel extends Model class FileModel extends Model
{ {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'oss_files';
const UPDATED_AT = null; const UPDATED_AT = null;
protected $fillable = ['type', 'module', 'name', 'path', 'ext', 'user_id', 'size']; protected $fillable = ['type', 'module', 'source_name', 'name', 'path', 'user_id', 'ext', 'size'];
} }
\ No newline at end of file
...@@ -43,59 +43,66 @@ class UploadOssService ...@@ -43,59 +43,66 @@ class UploadOssService
$this->config = $container->get(ConfigInterface::class); $this->config = $container->get(ConfigInterface::class);
$this->factory = $container->get(FilesystemFactory::class); $this->factory = $container->get(FilesystemFactory::class);
$ossConfig = $this->config->get('file.storage.oss'); $ossConfig = $this->config->get('file.storage.oss');
$this->urlPrefix = 'http://' . $ossConfig['bucket'] . '.' . $ossConfig['endpoint'] . '/'; $this->urlPrefix = 'https://' . $ossConfig['bucket'] . '.' . $ossConfig['endpoint'] . '/';
$this->appDev = $this->config->get('app_env'); $this->appDev = $this->config->get('app_env');
} }
/** /**
* 上传图片 * 上传图片
* @param \Hyperf\HttpMessage\Upload\UploadedFile $image * @param \Hyperf\HttpMessage\Upload\UploadedFile $image
* @param string $path * @param string $module
* @return array * @return array
* @throws \Meibuyu\Common\Exceptions\HttpResponseException * @throws \Meibuyu\Common\Exceptions\HttpResponseException
* @author Zero * @author chentianyu
*/ */
public function uploadImage(UploadedFile $image, string $path, string $userId) public function uploadImage(UploadedFile $image, string $module, int $userId, bool $uniqueFileName = false)
{ {
$ext = $image->getExtension();
$clientFilename = $image->getClientFilename();
$fileName = $uniqueFileName ? ($this->genUniqueFileName() . '.' . $ext) : $clientFilename;
$options = ['mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']]; $options = ['mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']];
$filePath = 'meibuyu/' . $this->appDev . "/$path/images/" . today() . "/$userId/" . $image->getClientFilename(); $filePath = 'oss2/' . $this->appDev . "/$module/images/" . today() . "/$userId/" . $clientFilename;
$this->upload($image, $filePath, $options); $this->upload($image, $filePath, $options);
$model = new FileModel(); $model = new FileModel();
$model = $model->newInstance([ $model = $model->newInstance([
'type' => 'image', 'type' => 'image',
'module' => '', 'module' => $module,
'user_id' => $userId, 'user_id' => $userId,
'size' => num_2_file_size($image->getSize()), 'source_name' => $clientFilename,
'name' => $image->getClientFilename(), 'name' => $fileName,
'path' => $this->urlPrefix . $filePath, 'path' => $this->urlPrefix . $filePath,
'ext' => $image->getExtension(), 'ext' => $ext,
'size' => num_2_file_size($image->getSize()),
]); ]);
$model->save(); $model->save();
return $model->toArray(); return $model->toArray();
} }
/** /**
* 上传文件 * 上传文件
* @param \Hyperf\HttpMessage\Upload\UploadedFile $image * @param \Hyperf\HttpMessage\Upload\UploadedFile $image
* @param string $path * @param string $module
* @return array * @return array
* @throws \Meibuyu\Common\Exceptions\HttpResponseException * @throws \Meibuyu\Common\Exceptions\HttpResponseException
* @author Zero * @author chentianyu
*/ */
public function uploadFile(UploadedFile $file, string $path, string $userId, array $options = []) public function uploadFile(UploadedFile $file, string $module, string $userId, bool $uniqueFileName = false, array $options = [])
{ {
$filePath = 'oss2/' . $this->appDev . "/$path/images/" . today() . "/$userId/" . $file->getClientFilename(); $ext = $file->getExtension();
$clientFilename = $file->getClientFilename();
$fileName = $uniqueFileName ? ($this->genUniqueFileName() . '.' . $ext) : $clientFilename;
$filePath = 'oss2/' . $this->appDev . "/$module/files/" . today() . "/$userId/" . $clientFilename;
$this->upload($file, $filePath, $options); $this->upload($file, $filePath, $options);
$model = new FileModel(); $model = new FileModel();
$model = $model->newInstance([ $model = $model->newInstance([
'type' => 'file', 'type' => 'file',
'module' => '', 'module' => $module,
'user_id' => $userId, 'user_id' => $userId,
'size' => num_2_file_size($file->getSize()), 'source_name' => $clientFilename,
'name' => $file->getClientFilename(), 'name' => $fileName,
'path' => $this->urlPrefix . $filePath, 'path' => $this->urlPrefix . $filePath,
'ext' => $file->getExtension(), 'ext' => $ext,
'size' => num_2_file_size($file->getSize()),
]); ]);
$model->save(); $model->save();
return $model->toArray(); return $model->toArray();
...@@ -103,13 +110,13 @@ class UploadOssService ...@@ -103,13 +110,13 @@ class UploadOssService
/** /**
* @param \Hyperf\HttpMessage\Upload\UploadedFile $file * @param \Hyperf\HttpMessage\Upload\UploadedFile $file
* @param $path * @param $filePath
* @param array $options * @param array $options
* @return bool * @return bool
* @throws \Meibuyu\Common\Exceptions\HttpResponseException * @throws \Meibuyu\Common\Exceptions\HttpResponseException
* @author Zero * @author chentianyu
*/ */
public function upload(UploadedFile $file, string $path, array $options = []) public function upload(UploadedFile $file, string $filePath, array $options = [])
{ {
if ($file->isValid()) { if ($file->isValid()) {
$options = array_merge(self::$options, $options); $options = array_merge(self::$options, $options);
...@@ -125,7 +132,7 @@ class UploadOssService ...@@ -125,7 +132,7 @@ class UploadOssService
try { try {
$oss = $this->factory->get('oss'); $oss = $this->factory->get('oss');
$stream = fopen($file->getRealPath(), 'r+'); $stream = fopen($file->getRealPath(), 'r+');
$res = $oss->writeStream($path, $stream); $res = $oss->writeStream($filePath, $stream);
is_resource($stream) && fclose($stream); is_resource($stream) && fclose($stream);
return $res; return $res;
} catch (FileExistsException $e) { } catch (FileExistsException $e) {
...@@ -136,4 +143,14 @@ class UploadOssService ...@@ -136,4 +143,14 @@ class UploadOssService
} }
} }
/**
* 生成唯一文件名
* @return string
* @author chentianyu
*/
public function genUniqueFileName()
{
return date('YmdHis') . uniqid();
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment