thinkphp6文件上传功能\多文件上传\文件验证 方法封装

官网文档知识点比较乱, 导致每次写上传都得去翻文档, 现直接写好一个上传方法 用到时直接调用即可, 支持多文件上传, 多文件验证

	/** 
	* 文件上传和验证
	* @author: sudden3<sudden3@foxmail.com>
	* 
	* @Param: string $filename 文件的参数名 filename
	* @Param: string $filepath 上传地址 例如 'image/logo'
	* @Param: string $rule     验证规则 请参照tp文档 https://www.kancloud.cn/manual/thinkphp6_0/1037639
	* 
	* @Return: array
	*/
  public function upload($filename ,$filepath, $rule)
  {
    $files = request()->file($filename);
    if (!is_array($files)) {
      $files = [$files];
      $isOne = true;
    }
    $error = ['code' => 200];
    foreach($files as $file) {
      try {
        validate([$filename => $rule])->check([$filename => $file]);
      } catch (ValidateException $e) {
        $error = array('code' => 500, 'msg' => $e->getMessage());
      break;
      }
    }
    if ($error['code'] === 200) {
      $fileList = [];
      foreach($files as $file) {
        $savename = \think\facade\Filesystem::disk('public')->putFile($filepath, $file);
        $savename = $this->tranPath($savename, true);
        $fileList[] = $savename;
      }
      if (count($files) === 1 && isset($isOne)) {
        $fileList = $fileList[0];
      }
      return ['code' => 200, 'fileName' => $fileList];
    }
  }

使用:

// 调用方法
$this->upload('file', 'image/article', 'fileSize:512000|fileExt:jpg,jpeg,png,bmp,webp|image');


// 返回: 
['code' => 200, 'fileName' => 'image/article/20200927/9a7fb6ef6617c5f1cf3e1e6401f5d1f3.png'];

// 支持多文件上传, 多文件上传成功后返回:
[
	"code" => 200
	"fileName" => [
		"image/article/20200927/9a7fb6ef6617c5f1cf3e1e6401f5d1f3.png",
		"image/article/20200927/d6c789623d0fc9d07338fbf87370e97e.png",
		"image/article/20200927/550941a9bbb06c1decd8b7949fd964af.png"
	]
]
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值