Thinkphp使用Layui的富文本编辑器(layedit)添加文章,上传图片教程

添加文章页面截图:

 文章显示页面截图:

前端 Html代码:

  <div class="layui-form-item">
        <label class="layui-form-label">内容</label>
        <div class="layui-input-block">
            <textarea id="content" name="content" style="display: none;"></textarea>
        </div>
  </div>   
<script>
layui.use(['form','upload', 'layedit','table', 'laydate','element'], function(){
    var form = layui.form,layer = layui.layer,layedit = layui.layedit
    ,laydate = layui.laydate,upload = layui.upload,element = layui.element,table = layui.table;     

    function goback(data){
        if(data.code=='1') window.history.go(-1);
    }  
	//上传图片,必须放在 创建一个编辑器前面
	layedit.set({
        uploadImage: {
            url: '{:url("@admin/article/uploadPic")}', //上传接口
            type: 'post'
        }
    });
	//建立编辑器
	var lb = layedit.build('content', {
	  height: 400 //设置编辑器的高度
	}); 

    form.on('submit(submit)', function(data){ 
		//获取编辑器内容
		data.field.content=layedit.getContent(lb);
		parent.$.fn.jcb.post("{$config['current_url']}",data.field,false,goback);  
		return false;
	}); 

});
</script>

后端 controller控制器代码:

    /**
    * 上传模块   
    */
    public function uploadPic()
    {
        $file = request()->file('file');   
        if($file){
            $info = $file->validate(['ext'=>$this->config['uploadtype']])->move(ROOT_PATH . 'public' . DS . 'uploads');          
            $data= array();
            if($info){ 
                $data['code'] = 0;
                $data['msg'] ='上传成功!';
                $data['data']['src'] ='/uploads/'.$info->getSaveName();  
            }else{                
                $data['code'] = 1;
                $data['msg'] ='上传失败,请检查文件类型是否允许上传!';
            }
            echo json_encode($data);
        }
    }
    /**
    * 添加文章模块   
    */
    public function add(){		
        if(request()->isPost()){
            $data=input('post.');
            //标题
            $title=trim($data['title']);
            //类型
            $typeId= trim($data['typeId']);
            //内容
            $content= trim($data['content']);
            //浏览次数
            $person= empty(trim($data['person']))? 0 : trim($data['person']);
            empty(trim($data['title'])) && $this->error('标题不能为空!');
            $updata['title'] = $title;
            $updata['typeId'] = $typeId;
            $updata['person'] = $person;
            $updata['content'] = $content;
            //作者
            $updata['athuor'] = "admin";	
            try{
                $resultid =Db::name('article')->insertGetId($updata);
			} catch (\Exception $e) {
                $this->error('新增失败!'.$e);
			}
			$this->success('新增成功!',url('@admin/article/index'));	 
        }else{ 
            return view();
        }
    }

 

已标记关键词 清除标记