tp5图片上传

假设表单代码如下:

<form action="/index/index/upload" enctype="multipart/form-data" method="post">
<input type="file" name="image" /> <br> 
<input type="submit" value="上传" /> 
</form> 

然后在控制器中添加如下的代码:

public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('image');

    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getFilename(); 
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }
}
public function add(){
        if(request()->isPost()){
            $data = input('post.');
            $article = new ArticleModel();
            if($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){

                    $thumb = "http://www.tp5bike.com/". DS . 'uploads'.'/'.$info->getSaveName();
                    $data['thumb'] = $thumb;
                }else{
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
            }
            $data['time'] = new Time();
            if($article->save($data)){
                $this->success('添加文章成功!',url('lst'));
            }else{
                $this->error('添加文章失败!');
            }
            dump($data);die;
            return;
        }
        $cate = new CateModel();
        $cateres = $cate->catetree();
        $this->assign('cateres',$cateres);
        return $this->fetch();
    }

猜你喜欢

转载自blog.csdn.net/qq_35285627/article/details/81029169