Commit 21acd8b5 authored by chentianyu's avatar chentianyu

UploadOss

parent ba69e79b
<?php
/**
* Created by PhpStorm.
* User: 王源
* Date: 2020/1/9
* Time: 15:08
*/
namespace Meibuyu\Micro\Service;
use Exception;
use Hyperf\DbConnection\Model\Model;
use Meibuyu\Micro\Helper;
class BaseService
{
/**
* @var Model
*/
protected $model;
/**
* 查找一个数据
* @param $id
* @return Model | array
*/
protected function find($id)
{
$model = $this->model->find($id);
return $model;
}
public function all(array $columns = ['*'], array $relations = []): array
{
return $this->model->with($relations)->get($columns)->toArray();
}
/**
* 获取一条数据
* @param int $id
* @param array $columns
* @param array $relations
* @return mixed
*/
public function get(int $id, array $columns = ['*'], array $relations = [])
{
return $this->model->with($relations)->find($id, $columns);
}
/**
* 插入一条数据
* @param array $params
* @return array
*/
public function insert($params)
{
try {
$res = $this->model->insert($params);
return Helper::success($res);
} catch (Exception $e) {
return Helper::fail('', $e->getMessage());
}
}
/**
* 新增一条数据
* @param array $params
* @return array
*/
public function create($params)
{
try {
$model = $this->model->newInstance($params);
$model->save();
return Helper::success($model);
} catch (Exception $e) {
return Helper::fail('', $e->getMessage());
}
}
/**
* 更新数据
* @param $id
* @param array $params
* @return array
*/
public function update($id, $params)
{
try {
$model = $this->find($id);
$model->fill($params);
$model->save();
return Helper::success($model);
} catch (Exception $e) {
return Helper::fail('', $e->getMessage());
}
}
/**
* 删除数据
* @param $id
* @return array
*/
public function delete($id)
{
try {
$model = $this->find($id);
$res = $model->delete();
if ($res) {
return Helper::success($res, '删除成功');
} else {
return Helper::fail($res, '删除失败');
}
} catch (Exception $e) {
return Helper::fail('', $e->getMessage());
}
}
}
<?php
/**
* Created by PhpStorm.
* User: Zero
* Date: 2021/06/24
* Time: 15:59:06
*/
namespace App\Services;
use App\Model\File;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpMessage\Upload\UploadedFile;
use League\Flysystem\FileExistsException;
use Meibuyu\Micro\Exceptions\HttpResponseException;
use Meibuyu\Micro\Model\Auth;
use Psr\Container\ContainerInterface;
class UploadOssService
{
/**
* @var FilesystemFactory
*/
private $factory;
/**
* @var ConfigInterface
*/
private $config;
/**
* @var string
*/
private $urlPrefix;
/**
* @var string
*/
private $appDev;
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');
$this->urlPrefix = 'http://' . $ossConfig['bucket'] . '.' . $ossConfig['endpoint'] . '/';
$this->appDev = $this->config->get('app_env');
}
/**
* @param \Hyperf\HttpMessage\Upload\UploadedFile $image
* @param string $path
* @return array
* @throws \Meibuyu\Micro\Exceptions\HttpResponseException
* @author Zero
*/
public function uploadImage(UploadedFile $image, string $path = 'default')
{
$options = ['mime' => ['jpeg', 'png', 'gif', 'jpg', 'svg']];
$userId = Auth::id();
$filePath = $this->appDev . "/upload/$path/images/" . today() . "/$userId/" . $image->getClientFilename();
$this->upload($image, $filePath, $options);
$model = new File();
$model = $model->newInstance([
'user_id' => $userId,
'size' => num_2_file_size($image->getSize()),
'name' => $image->getClientFilename(),
'path' => $this->urlPrefix . $filePath,
'ext' => $image->getExtension(),
]);
$model->save();
return $model->toArray();
}
/**
* @param \Hyperf\HttpMessage\Upload\UploadedFile $file
* @param $path
* @param array $options
* @return bool
* @throws \Meibuyu\Micro\Exceptions\HttpResponseException
* @author Zero
*/
public function upload(UploadedFile $file, $path, array $options = [])
{
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+');
$res = $oss->writeStream($path, $stream);
is_resource($stream) && fclose($stream);
return $res;
} catch (FileExistsException $e) {
throw new HttpResponseException($e->getMessage());
}
} else {
throw new HttpResponseException('文件无效');
}
}
}
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