springmvc + jsp integrates Baidu rich text ueditor editor to upload pictures

The version used is 1.4.3.3 and the framework is ssm

File download link https://download.csdn.net/download/qq_39313596/13130543

 

The jar that needs to be relied on If it is maven, please add the corresponding ueditor maven warehouse in the pom. No download and need to install it to the maven warehouse.

       <dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20160810</version>
		</dependency>
 

 

First copy the contents inside to a static file

Such as

The page jsp code needs to introduce 3 js  


    <script type="text/javascript" charset="utf-8" src="<%=basePath%>js/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="<%=basePath%>js/ueditor/ueditor.all.min.js"> </script>
    <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" src="<%=basePath%>js/ueditor/lang/zh-cn/zh-cn.js"></script>



<body id="">

<div>
<h1>完整demo</h1>
<script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
</div>



<script>
    //实例化编辑器
    //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
    // var ue = UE.getEditor('editor');
    var ue = UE.getEditor('editor', {
        toolbars: [
            [
                //'anchor', //锚点
                'undo', //撤销
                'redo', //重做
                'bold', //加粗
                'indent', //首行缩进
                //'snapscreen', //截图
                'italic', //斜体
                'underline', //下划线
                'strikethrough', //删除线
                'subscript', //下标
                'fontborder', //字符边框
                'superscript', //上标
                'formatmatch', //格式刷
                'source', //源代码
                'blockquote', //引用
                'pasteplain', //纯文本粘贴模式
                'selectall', //全选
            //    'print', //打印
                'preview', //预览
                'horizontal', //分隔线
                'removeformat', //清除格式
                'time', //时间
                'date', //日期
                'unlink', //取消链接
                'insertrow', //前插入行
                'insertcol', //前插入列
              //  'mergeright', //右合并单元格
               // 'mergedown', //下合并单元格
                'deleterow', //删除行
                'deletecol', //删除列
               // 'splittorows', //拆分成行
              //  'splittocols', //拆分成列
               // 'splittocells', //完全拆分单元格
              //  'deletecaption', //删除表格标题
               // 'inserttitle', //插入标题
             //   'mergecells', //合并多个单元格
             //   'deletetable', //删除表格
                'cleardoc', //清空文档
                //'insertparagraphbeforetable', //"表格前插入行"
                'insertcode', //代码语言
                'fontfamily', //字体
                'fontsize', //字号
                'paragraph', //段落格式
                'simpleupload', //单图上传
              //  'insertimage', //多图上传
             //   'edittable', //表格属性
             //   'edittd', //单元格属性
                'link', //超链接
               // 'emotion', //表情
                'spechars', //特殊字符
                'searchreplace', //查询替换
               // 'map', //Baidu地图
              //  'gmap', //Google地图
              //  'insertvideo', //视频
              //  'help', //帮助
                'justifyleft', //居左对齐
                'justifyright', //居右对齐
                'justifycenter', //居中对齐
                'justifyjustify', //两端对齐
                'forecolor', //字体颜色
                'backcolor', //背景色
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                //'fullscreen', //全屏
                'directionalityltr', //从左向右输入
                'directionalityrtl', //从右向左输入
                'rowspacingtop', //段前距
                'rowspacingbottom', //段后距
                'pagebreak', //分页
                //'insertframe', //插入Iframe
                'imagenone', //默认
                'imageleft', //左浮动
                'imageright', //右浮动
               // 'attachment', //附件
                'imagecenter', //居中
                //'wordimage', //图片转存
                'lineheight', //行间距
                'edittip ', //编辑提示
               // 'customstyle', //自定义标题
               // 'autotypeset', //自动排版
                //'webapp', //百度应用
                'touppercase', //字母大写
                'tolowercase', //字母小写
               // 'background', //背景
               // 'template', //模板
             //   'scrawl', //涂鸦
               // 'music', //音乐
                //'inserttable', //插入表格
                //'drafts', // 从草稿箱加载
                // 'charts', // 图表
            ]
        ],
        autoHeightEnabled: true,
        autoFloatEnabled: true,
       // enableAutoSave: false, //禁止自动保存
       // autoSyncData: false,//自动同步编辑器要提交的数据
    });
    /*  ue.ready(function () {
          $(".edui-editor-messageholder.edui-default").css({ "visibility": "hidden" });
      });*/
    // 文件上传配置
    ue.wordCount = true;
    ue.maximumWords = 1500
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage' || action == 'uploadvideo') {
            return "${pageContext.servletContext.contextPath}/ueditor/ueditorUploadFile.do"; //改成您自己的上传接口
            //'http://localhost:8080/imgUpload';为方法imgUpload的访问地址
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
</script>
</body>

Back-end code sftp upload


    /***
     * ueditor 图片 公用上传接口
     * @returnarray(
     * "state" => "",
     * 上传状态,上传成功时必须返回"SUCCESS"
     * "url" => "",            //返回的地址
     * "title" => "",          //新文件名
     * "original" => "",       //原始文件名
     * "type" => ""            //文件类型
     * "size" => "",           //文件大小
     * @throws IOException
     * @throws Exception
     */
    @RequestMapping(value = "ueditorUploadFile.do", method = {RequestMethod.POST, RequestMethod.GET})
    public Map<String, Object> ueditorUploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html");
        response.setContentType("text/html; charset=UTF-8");
        Map<String, Object> map = new HashMap<>();
        SFTPUtils sftp = null;
        String filepath = "images/ueditor";
        MultipartHttpServletRequest mReq = null;
        MultipartFile mfile = null;
        String fileName = "";
        String originalFileName = "";
        try {
            mReq = (MultipartHttpServletRequest) request;
            // 从config.json中取得上传文件的ID "imageFieldName": "upfile", /* 提交的图片表单名称 */
            mfile = mReq.getFile("upfile");
            if (!mfile.isEmpty()) {
                originalFileName = mfile.getOriginalFilename();
                String filePath = (String) PropertiesConfigurer.propertiesMap.get("url");

                File file = new File(filepath);
                boolean exists = file.exists();
                if (!exists) file.mkdirs();
             
                sftp = new SFTPUtils((String) PropertiesConfigurer.propertiesMap.get("host")
                        , (String) PropertiesConfigurer.propertiesMap.get("user")
                        , (String) PropertiesConfigurer.propertiesMap.get("pwd"));
                sftp.connect();
                String dt = String.valueOf(new StringBuffer(String.valueOf(System.currentTimeMillis())).reverse());
                if (mfile.getOriginalFilename() != null && mfile.getOriginalFilename().trim().length() > 0 && checkFile(mfile.getOriginalFilename().split("\\.")[1])) {
                    fileName = IdUtil.objectId() + dt + Math.random() + "." + mfile.getOriginalFilename().split("\\.")[1];
                    sftp.uploadFile(filepath, fileName, mfile);
                    //图片url
                    map.put("state", "SUCCESS"); // UEDITOR的规则:不为SUCCESS则显示state的内容
                    map.put("url", filePath + filepath + "/" + fileName); //能访问到你现在图片的路径
                    map.put("title", fileName);
                    map.put("original", originalFileName);
                    map.put("size", String.valueOf(mfile.getSize()));
                    //map.put("type", ".jpg");
                    map.put("type", "." + mfile.getOriginalFilename().split("\\.")[1]);
                    return map;
                } else {
                    map.put("state", "文件不存在!"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
                    map.put("url", "");
                    map.put("title", "");
                    map.put("original", "");
                    map.put("size", "0");
                    map.put("type", "");
                    return map;
                }
            } else {
                map.put("state", "文件不存在!"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
                map.put("url", "");
                map.put("title", "");
                map.put("original", "");
                map.put("size", "0");
                map.put("type", "");
                return map;
            }
        } catch (Exception ex) {
            logger.error("保存出现异常", ex);
            map.put("state", "文件上传失败!"); //在此处写上错误提示信息,这样当错误的时候就会显示此信息
            map.put("url", "");
            map.put("title", "");
            map.put("original", "");
            map.put("size", "0");
            map.put("type", "");
            return map;
        } finally {
            sftp.disconnect();
        }
    }

effect

 

Guess you like

Origin blog.csdn.net/qq_39313596/article/details/109853723