本例以上传图片为模板
前端代码:
<div class="form-group"> <label for="title_img" class="col-sm-2 control-label">标题图片</label> <div class="col-sm-10"> <label for="title_img">选择上传文件</label> <input type="file" id="title_img" name="title_img"> </div> </div>
后端代码:
$file = Request::file('title_img');
// halt($file);
//file 包含当前文件所有本地信息
if($file){
$info = $file->validate([
'size'=>100000,
'ext'=>'jpeg,jpg,png,gif'
//动态方法move 从本地将文件移动至服务器
])->move('uploads');
// halt($info);
//包含所有在服务器上的文件信息(文件名已被修改)
if($info){
$data['title_img'] = $info->getSaveName();
}else{
//file->getError()包含上传错误信息
$this->error($file->getErrot());
}
}else{
echo "<script>alert('请上传标题图片');window.history.back(-1);</script>";
}步骤:
从请求获取当前文件;
验证上传文件;
用控制器动态方法将文件移动至服务器指定目录;
总结:
//当前获取到的 file 为本地 文件信息
$file = Request :: file("$data['img']");//移动成功后 info 为服务器 文件信息 文件名已被更改
$info = $this->validate([$rule])->move('服务器指定目录');
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号