在thinkphp中的文件上传功能,添加验证器的过程中.踩得小坑,简单记录。
具体内容如下
代码如下.
视图层 就是简单的form表单,用来上传文件。
<form action="/admin/files/upFile" enctype="multipart/form-data" method="post">
<input type="file" name="image" /> <br>
<button type="submit" >上传 </button>
</form>
控制器层用来接收传进来的数据以及返回信息.
public function upFile(){
if (\request()->method() == "POST") {
$file = request()->file();
// halt($file);
$rt = \app\admin\model\Files::uploadFile($file);
if ($rt['code'] == 0) {
$this->success($rt['msg']);
} else {
$this->error($rt['msg']);
}
}
$this->error("错误的请求方法","/index");
// halt($file);
}
这里我将具体的处理代码放在了模型当中。存在问题的代码如下,
public static function uploadFile($file)
{
try {
//定义上传文件大小
$size = 2000*1024;
//验证器检测
validate(['image'=>"image|fileSize:$size"])->check($file);
//保存文件 到public配置下的avatar目录下
$savename = \think\facade\Filesystem::disk("public")->putFile( 'avatar', $file);
// halt($savename);
//定义数组信息
$arr = ["code"=>0,'msg'=>"上传成功"];
}catch (ValidateException $e){
$arr = ["code"=>0,'msg'=>$e->getError()];
}catch (\Exception $e){
$arr = ["code"=>2,'msg'=>'系统错误'];
}
return $arr;
}
问题出现的原因主要是validate验证器接收的只能为数组,那么我就在控制器
传入参数的时候,传入的内容就为数组.
$file = request()->file();
即未去定义name
, halt输出可以看到**file∗∗为数组。验证器验证正常,但是‘putFile‘方法就会产生如下错误。这里我的解决方法是在验证器验证成功之后,在重新获取file**为数组。
验证器验证正常,但是`putFile`方法就会产生如下错误。
这里我的解决方法是在验证器验证成功之后,在重新获取file∗∗为数组。验证器验证正常,但是‘putFile‘方法就会产生如下错误。这里我的解决方法是在验证器验证成功之后,在重新获取file.
Model层代码修改后如下,
public static function uploadFile($file)
{
try {
//定义上传文件大小
$size = 2000*1024;
//验证器检测
validate(['image'=>"image|fileSize:$size"])->check($file);
//重新定义$file
$file = request()->file("image");
//保存文件 到public配置下的avatar目录下
$savename = \think\facade\Filesystem::disk("public")->putFile( 'avatar', $file);
// halt($savename);
//定义数组信息
$arr = ["code"=>0,'msg'=>"上传成功"];
}catch (ValidateException $e){
$arr = ["code"=>0,'msg'=>$e->getError()];
}catch (\Exception $e){
$arr = ["code"=>2,'msg'=>'系统错误'];
}
return $arr;
}
重新上传一个符合符合要求的文件
反之
暂时没有想到更好的解决方法,希望各位大佬多多指点。