stevema / laravel-upload
自定义一个上传服务[整合本地、七牛云、阿里云、腾讯云] 开发环境: PHP:8.1 配合laravel使用
v1.0.0
2023-08-31 15:07 UTC
Requires
- aliyuncs/oss-sdk-php: >=2.4
- qcloud/cos-sdk-v5: ^2.6
- qiniu/php-sdk: ^7.3
This package is not auto-updated.
Last update: 2025-01-02 21:33:01 UTC
README
介绍
自定义一个上传服务[整合本地、七牛云、阿里云、腾讯云] 开发环境: PHP:8.1 配合laravel使用
安装教程
# 安装
$ composer require stevema/laravel-upload
使用说明
# 1、生成配置文件
$ php artisan vendor:publish --tag="upload"
# 2、修改配置文件 /config/afs.php 或在 /.env 文件中添加配置
#UPLOAD
UPLOAD_DEFAULT=local
# local aliyun qiniu qcloud
UPLOAD_VALIDATE=Stevema\Upload\UploadValidate
#UPLOAD_QINIU
UPLOAD_QINIU_BUCKET=
UPLOAD_QINIU_ACCESS_KEY=
UPLOAD_QINIU_SECRET_KEY=
UPLOAD_QINIU_DOMAIN=
#UPLOAD_ALIYUN
UPLOAD_ALIYUN_BUCKET=
UPLOAD_ALIYUN_ACCESS_KEY_ID=-
UPLOAD_ALIYUN_ACCESS_KEY_SECRET=
UPLOAD_ALIYUN_DOMAIN=
#UPLOAD_QCLOUD
UPLOAD_QCLOUD_BUCKET=
UPLOAD_QCLOUD_REGION=
UPLOAD_QCLOUD_SECRET_ID=
UPLOAD_QCLOUD_SECRET_KEY=
UPLOAD_QCLOUD_DOMAIN=
目录说明
├─ src
│ ├─ Config # 配置文件目录
│ │ └─ config.php # 配置文件
│ ├─ Engine # 存储引擎文件
│ │ └─ Aliyun.php # 阿里云OSS引擎
│ │ └─ Local.php # 本地引擎
│ │ └─ Qcloud.php # 腾讯云COS引擎
│ │ └─ Qiniu.php # 七牛云引擎
│ │ └─ Server.php # 公共引擎-其他引擎都继承它
│ ├─ Facades # 门面文件目录
│ │ └─ Upload.php # 门面
│ └─ helper.php # 帮助文件
│ └─ UploadException.php # 异常类
│ └─ UploadManage.php # 项目主文件
│ └─ UploadProvider.php # 服务提供者类
│ └─ UploadValidate.php # 文件验证类
└─ composer.json # 配置
使用方式
# 引入门面
use Stevema\Facades\Upload;
use Stevema\Upload\UploadValidate;
# 随便加一个路由
Route::get('/upload', function(){
// $upload = Upload::storage();
// $upload = app('upload');
// $upload = upload();
# 上面这三种方式都能拿到upload类
// $upload->storage('local');// 切换引擎 可以切换其它的引擎
$save_dir = 'uploads/images';
$upload = app('upload');
# 可以自己指定文件验证 - 也可以不指定 走默认
// $validateClassName=UploadValidate::class;
// if($validateClassName) {
// $upload->setUploadValidate($validateClassName);
// }
# 写入文件 - 上传的文件 file是上传文件的字段名
$upload->setUploadFile('file');
if (!$upload->upload($save_dir)) throw new \Exception($upload->getError());
$fileName = $upload->getFileName();
$fileInfo = $upload->getFileInfo();
// 处理文件名称
if (strlen($fileInfo['name']) > 128) {
$file_name = substr($fileInfo['name'], 0, 123);
$file_end = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
$fileInfo['name'] = $file_name.$file_end;
}
// 具体路径
$uri = $save_dir . '/' . str_replace("\\","/", $fileName);
$uri = $upload->getFileUrl($uri);
return response()->json([
'uri' => $uri,
'size' => $fileInfo['size'],
'name' => $fileInfo['name'],
'mime' => $fileInfo['mime'],
'ext' => $fileInfo['ext'],
]);
# 或者使用helper来执行上传
$input_name = 'file';//上传文件的input的key
$save_dir = 'uploads/images/';//保存文件的路径 默认:'uploads/'.date("Y/md")
$validate = null;//指定上传验证 默认:null
$info = upload_file($input_name, $save_dir, $validate);
dd($info);
// [
// 'uri' => $uri,
// 'size' => $fileInfo['size'],
// 'name' => $fileInfo['name'],
// 'mime' => $fileInfo['mime'],
// 'ext' => $fileInfo['ext'],
// ]
});