控制器层:
public functionadd(){
if(request()->isPost()){
$data = input('post.');
$artile = new ArticleModel();
$file =request()->file('thumb');
if($file){
$info =$file->move(ROOT_PATH . 'public' . DS . 'uploads');
if($info){
// 成功上传后 获取上传信息
//$data['thumb'] = ROOT_PATH .'public' . DS . 'uploads/'.$info->getSaveName();
$data['thumb'] ='http://127.0.0.1/thinkphp5/public/uploads/'.$info->getSaveName();
}else{
// 上传失败获取错误信息
echo $file->getError();
}
}
if($artile->save($data)){
$this->success('添加文章成功!',url('lst'));
}else{
$this->error('添加文章失败!');
}
return;
}
$cate = new CateModel();
$cateres = $cate->catetree();
$this->assign('cateres',$cateres);
return view();
}
在模型层中使用前置事件上传图片:
protected static function init()
{
Article::event('before_insert', function ($data) {
$file =request()->file('thumb');
if($file){
$info =$file->move(ROOT_PATH . 'public' . DS . 'uploads');
if($info){
// 成功上传后 获取上传信息
//$data['thumb'] = ROOT_PATH . 'public' . DS .'uploads/'.$info->getSaveName();
$data['thumb'] ='http://127.0.0.1/thinkphp5/public/uploads/'.$info->getSaveName();
}else{
// 上传失败获取错误信息
echo$file->getError();
}
}
});
}