群控系统服务端开发模式-应用开发-文件上传功能开发
一、文件上传路由
在根目录下route文件夹中app.php文件中,添加文件上传功能路由,代码如下:
Route::post('upload/file','common.Upload/file');// 上传文件接口
二、功能代码开发
在根目录下app文件夹下common文件夹中创建上传控制器并命名为Upload,代码如下:
<?php
/*** 上传* User: 龙哥·三年风水* Date: 2024/11/4* Time: 10:14*/
namespace app\controller\common;
use app\controller\Base;
use app\model\param\Upload as ParamUpload;
use Error\BaseError;
use think\exception\ValidateException;
use Upload\UploadFactory;class Upload extends Base
{//上传文件public function file(){$file = $this->request->file();$type = $this->request->param('type');try{$files = $file['file'];//查出上传设置$uploadparam = ParamUpload::dataFind(['id' => 1],'upload_type,checked_images,checked_videos,checked_filedocs,upload_number');//当下验证后缀$fileExt = [];//指定类型switch ($type){case 'image':$fileExt = $uploadparam['checked_images'];break;case 'video':$fileExt = $uploadparam['checked_videos'];break;case 'filedoc':$fileExt = $uploadparam['checked_filedocs'];break;default:throw new ValidateException('不支持的通道');break;}//验证validate(['file'=>'fileSize:'.($uploadparam['upload_number'] * 1024 * 1024).'|fileExt:'.$fileExt])->check($file);//获取文件后缀名$fileExtName = $files->getOriginalExtension();//新的文件名$fileName = str_replace('.'.$fileExtName,'',$files->getOriginalName());//截取文件后缀名$format = '.'.$fileExtName;//截取文件后缀名如 (.jpg)//原文件$primaryFileName = $fileName.$format;//加密后的文件$encryptionFileName = sha1(date('YmdHis', time()) . uniqid()) . $format;//要上传的路径$object = date('Y-m-d').'/'.$encryptionFileName;//临时文件地址$filePath = $files->getRealPath();//计算文件大小$fileSize = sprintf("%01.2f", $files->getSize()/(1024*1024));//调用工厂$uploadFactory = new UploadFactory();//选择通道$uploadHandle = $uploadFactory->getUploadHandle();$res = $uploadHandle->uploadFile($object,$uploadparam['upload_type'] == 1 ? $files : $filePath);$data['url'] = $res;$data['primary_fileName'] = $primaryFileName;$data['encryption_fileName'] = $encryptionFileName;$data['fileName_size'] = $fileSize;$data['fileName_type'] = $fileExtName;return succ('上传成功',$data);}catch (ValidateException $e){throw new BaseError($e->getMessage(),50000,200);}}
}
三、测试
通过测试,发现一个错误,在上传文件工厂控制类里面。第一个就是参数错误,第二个是调用上传通道错误。《群控系统服务端开发模式-应用开发-上传工厂开发》中代码已修改。