计算机网络/计算机科学与应用/系统/运维/开发

tp5.1 修改图片

public function doEdit($id = 0)
    {
        if(request()->isPost()){
            // 获取所有提交的数据
            $data = input('post.');
            try {
                $file = request()->file('img');
                // 判断是否有文件上传
                if($file){
                    $img =  Db::name('news')->where('id', $id)->value('img');
                    // 如果数据库中有图片值,则删除物理图片
                    if($img){
                        $imgUrl = Env::get('root_path') . 'public/uploads' . $img;
                        if(file_exists($imgUrl)){
                            @unlink($imgUrl);
                        }else{
                            return resMsg(0,'图片物理路径不存在!');
                        }
                    }else{
                        return resMsg(0,'数据库中图片路径为空!');
                    }
                    // 获取图片
                    $info = $file->validate(['size'=>1024*1024,'ext'=>'jpg,jpeg,png,gif'])->move( '../public/uploads');
                    if($info){
                        $data['img'] = str_replace("\\","/",$info->getSaveName());
                    }
                }
            }catch (\Exception $e) {
            }
            // 数据验证
            $validate = new newsValidate();
            if(!$validate->scene('edit')->check($data)){
                return resMsg(0,$validate->getError());
            }
            // 更新数据
            try {
                $newsModel = new NewsModel();
                $result = $newsModel->allowField(true)->save($data,['id' => $id]);
                if( $result){
                    return resMsg(1,'文章更新成功',url('lst'));
                }else{
                    return resMsg(0,'文章更新失败');
                }
            }catch (\Exception $e) {
                return resMsg(0,$e->getMessage());
            }
        }
    }


好的习惯,排名第一的是:自律;排名第二的是:终身学习;排名第三的是:保持运动。拥有这三种习惯,美好人生垂手可得。

评论

^