The use and echo of rich text in front-end and background (ueditor)


Renderings:
insert image description here
insert image description here
insert image description here

How to configure ueditor at the front end

下载ueditor资源文件地址:
Ueditor resource file compression package download

After downloading and decompressing, put it in the js folder
insert image description here

json file comment

json文件注释需要更具自己的相关信息来修改,比如保存图片地址,访问图片前缀

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    
    
    /* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "", /* 图片访问路径前缀 */
    "imagePathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/ueditor/php/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/php/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 512000000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/php/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/php/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}

提示:以下是本篇文章正文内容,下面案例可供参考

One, html, js reference ueditor

First create this tag in your html file
insert image description here

<div class="row fontawesome-icon-list">

    <div class="fa-hover col-lg-3 col-md-6">
        <form class="create_form">

            <textarea  id="editor"  name="summary"  style="width:1140px;height:350px;"></textarea>


        </form >

    </div>
</div>

Then import the js file on this page according to your own path
insert image description here
, then open the js file you created and fill in the configuration

var create_product = {
    
    
   
    init: function () {
    
    
        create_product.evenBin();
        create_product.initEditor();
        
    },
    evenBin: function () {
    
    

        var btn_target = jQuery(this);
        var ue = UE.getEditor('editor');
        var content=true;

        // 提交内容
        jQuery(" #submit_affirm1").click(function () {
    
    
            // 获得富文本的内容,提交给后台后台需要保存在数据
            var text = jQuery.trim(ue.getContent());
            jQuery.ajax({
    
    
                url:  window.location.href,
                type: "POST",
                data: {
    
    
                    'text': text,
                },
                dataType: 'json',
                success: function (res) {
    
    
                        var response = JSON.parse(res);
                        alert(response.msg);
                        if (response.code == 200){
    
    
                            location.replace('/admin/login');
                        }

                }

            });


        })
    },
    initEditor: function () {
    
    
        var that = this;
        var url=document.domain+"/admin/upload";

        that.ue = UE.getEditor('editor', {
    
    
            toolbars: [
                ['undo', 'redo', '|',
                    'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight'],
                ['customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                    'directionalityltr', 'directionalityrtl', 'indent', '|',
                    'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                    'link', 'unlink'],
                ['imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                    'insertimage', 'insertvideo', '|',
                    'horizontal', 'spechars', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']

            ],
            //设置多久自动保存
            enableAutoSave: true,
            saveInterval: 60000,
            //关闭元素路径
            elementPathEnabled: false,
            zIndex: 4,
            //图片上传的图片地址
            serverUrl:"/admin/upload",
        });


    },
}


window.onload = function () {
    
    

    create_product.init();

};

上面配置好后,打开此页面会向服务器发送一个请求: 一定要后端接受这个请求并将upload_config.json文件返回出来,不然无法使用图片功能,文章的第二节有后台的详细的处理方式

Upload image configuration request:
insert image description here
Request for the image above:
insert image description here
从上面的截图可以分析出图片配置和上传图片的发送的action参数不一样,因此一个接口里面根据action参数值不一样来判断是上传还是要配置

2. The backend returns the json file of ueditor

1. Configure the interface that accepts ueditor

Take php as an example: In fact, it doesn’t matter what language it is, as long as the request sent by the front end can be accepted, it’s ok, and then accept the address of the picture to save

The code is as follows (example):
It doesn’t matter which class it is written in, just configure this interface in the route.php file, and you can come to this method when accessing
注意看对应ueditor的json文件注释,将参数修改成自己的

    //处理富文本上传的图片
    public function uploads()
    {
    
    
        $action = $_GET['action'];
		
		//返回upload_config.json文件,注意看对应文件的注释,将参数修改成自己的
        if ($action == "config") {
    
    
        	//配置
            $config_path =ROOT_PATH . 'public' . DS . "static" . DS ."js" . DS ."ueditor" . DS ."upload_config.json";
			//读取文件
            $json_string = file_get_contents($config_path);
          
            return $json_string ;

        }

        //上传图片
        if ($action == "uploadimage") {
    
    


            return $this->uploadimage();

        }

        //在线管理图片
        if ($action == "listimage"){
    
    
            return $this->listimage();
        }
        return "Q_Q!";
    }
        //处理富文本编辑上传的图片
    public function uploadimage()
    {
    
    
        $mistake=[
            "code"=>-1,
            "state"=>"SUCCESS",
            "url"=>""
        ];
        //接收图片
        $file = request()->file("upfile");

        if ($file){
    
    
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
    
    
                //上传成功  拼接图片的访问路径  /uploads/20190709/fssdsahfdskasa.jpg
                $goods_logo = DS . 'uploads' . DS . $info->getSaveName();


                $url=str_replace("\\","/",  $goods_logo);

                $mistake["code"] = 200;
                $mistake["url"]=$url;
                Db::query("insert into pro_file(`url`) values(?)",[$url]);

            }else{
    
    
                $mistake["code"]=-1;
                $mistake["state"]="上传错误";
            }
            return $mistake;
        }
    }

    // 在线管理图片
    public function listimage(){
    
    
        $resp =["state"=> "SUCCESS", "start"=> "", "total"=> ""] ;
        //获取当前域名
        $yuming=$this->domain();

        //接收当前参数
        $start = $_GET['start'];
        $page_size=$_GET['size'];

        //查询数据库中所有的图片
        $db=Db::query("select * from pro_file limit $page_size offset $start ");
        $list=[];
        $i=0;
        foreach ($db as $val){
    
    

            $list[$i]["url"]=$yuming.$val["url"];
            $i+=1;
        }
        $resp["list"]=$list;
        $resp["start"]=$start;
        $resp["total"]=count($db);
        return $resp;
    }

3. Return

回显的时候只需要给后台发送接口,后台返回ueditor提交的html代码,然后用js将值渲染到页面上

  //回显
        jQuery.ajax({
    
    
            url: "/admin/updata_products",
            type:"GET",
            dataType:'json',
            success:function (res) {
    
    
                var response = JSON.parse(res);
                if (response.code == 200) {
    
    
                  
                    document.getElementsByClassName("summary")[0].innerHTML=response.desc;
                    that.initEditor();
        

Guess you like

Origin blog.csdn.net/qq_48082548/article/details/128625105