富文本 KindEditor 前后端文字图片交互例子(亲测可用)

先放效果图:

格式如下:

后台获得:

下面是代码实现:

html:

<!doctype html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;  charset=UTF-8" />
        <title>Default Examples</title>
        <style>
            form {
                margin: 0;
            }
            textarea {
                display: block;
            }
        </style>
        <link rel="stylesheet" href="../static/css/default.css" type="text/css">
        <script type="text/javascript" src="../static/js/kindeditor-all.js"></script>
        <script type="text/javascript" src="../static/js/jquery.min.js"></script>
        <script type="text/javascript" src="../static/js/zh_CN.js"></script>
        <script type="text/javascript">
            var editor;
            KindEditor.ready(function(K) {
                 window.editor = K.create('#editor_id', {
                    //这里是指定的文件上传input的的属性名
                                filePostName: "myFileName",
                    //这里就是指定文件上传的请求地址,上面也已经说了,upload_json.jsp就相当去一个servlet去进行保存文件,这个地方很重要
                                uploadJson: 'http://localhost:8080/User/inserKingedusImg',
                                resizeType: 1,
                                allowPreviewEmoticons: true,
                                allowImageUpload: true,
                            });
                /* editor = K.create('textarea[name="content"]', {                    
                    allowFileManager : true,
                }); */
                K('input[name=getHtml]').click(function(e) {
                    var asp = editor.html();
                    console.log(asp);
                    var announcement_mag = encodeURIComponent(asp);
                    $.ajax({
                        url : "http://localhost:8080/User/inserKingedus?announcement_mag="+announcement_mag,
                        type : "post",
                        dataType : "json",
                        success : function(data) {
                            alert(data.result);    
                        },
                         error : function(msg) {
                                alert("ajax连接异常:" + msg);
                            }
                    }); 
                    alert(editor.html());
                });
                K('input[name=isEmpty]').click(function(e) {
                    alert(editor.isEmpty());
                });
                K('input[name=getText]').click(function(e) {
                    var announcement_mag = editor.text();
                    console.log(announcement_mag);
                     $.ajax({
                        url : "http://localhost:8080/User/inserKingedus?announcement_mag="+announcement_mag,
                        type : "post",
                        dataType : "json",
                        success : function(data) {
                            alert(data.result);    
                        },
                         error : function(msg) {
                                alert("ajax连接异常:" + msg);
                            }
                    });
                    alert(editor.text());
                });
                K('input[name=selectedHtml]').click(function(e) {
                    alert(editor.selectedHtml());
                });
                K('input[name=setHtml]').click(function(e) {
                    editor.html('<h3>Hello KindEditor</h3>');
                });
                K('input[name=setText]').click(function(e) {
                    editor.text('<h3>Hello KindEditor</h3>');
                });
                K('input[name=insertHtml]').click(function(e) {
                    editor.insertHtml('<strong>插入HTML</strong>');
                });
                K('input[name=appendHtml]').click(function(e) {
                    editor.appendHtml('<strong>添加HTML</strong>');
                });
                K('input[name=clear]').click(function(e) {
                    editor.html('');
                });
            });
        </script>
    </head>
    <body>
        <h3>默认模式</h3>
        <form>
            <textarea id="editor_id" name="content" style="width:800px;height:400px;visibility:hidden;">KindEditor</textarea>
            <p>
                <input type="button" name="getHtml" value="取得HTML" />
                <input type="button" name="isEmpty" value="判断是否为空" />
                <input type="button" name="getText" value="取得文本(包含img,embed)" />
                <input type="button" name="selectedHtml" value="取得选中HTML" />
                <br />
                <br />
                <input type="button" name="setHtml" value="设置HTML" />
                <input type="button" name="setText" value="设置文本" />
                <input type="button" name="insertHtml" value="插入HTML" />
                <input type="button" name="appendHtml" value="添加HTML" />
                <input type="button" name="clear" value="清空内容" />
                <input type="reset" name="reset" value="Reset" />
            </p>
        </form>
    </body>
</html>

后台:

将图片上传服务器:

/*
     * kingedu富文本获取前台输入数据
     */
    @RequestMapping(value = "/inserKingedusImg")
    @ResponseBody
    public Map<String, Object> inserKingedusImg(@RequestParam(value = "myFileName") MultipartFile mf,
            HttpServletRequest request) throws ServletException, IOException {
        String realPath = request.getSession().getServletContext().getRealPath("myFileName");
        // 获取源文件
        String filename = mf.getOriginalFilename();
        String[] names = filename.split("\\.");//
        String tempNum = (int) (Math.random() * 100000) + "";
        String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];
        File targetFile = new File(realPath, uploadFileName);// 目标文件
        // 开始从源文件拷贝到目标文件
        // 传图片一步到位
        try {
            mf.transferTo(targetFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println(uploadFileName);
        map.put("error",0);

// 这里应该是项目路径
        map.put("url", "http://localhost:8080/static/myFileName/" + uploadFileName);
        System.out.println(map.get("url"));
        return map;// 将图片地址返回
    }

点击后台拿到html格式数据:

/*
     * kingedu富文本获取前台输入数据
     */
    @RequestMapping(value = "/inserKingedus")
    @ResponseBody
    public Map<String, Object> inserKingedus(String announcement_mag) {
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println(announcement_mag);
        map.put("result", "true");
        return map;
    }

如果上传成功图片无法显示等问题:参考我之前的一篇:富文本 wangEditor 前后端交互例子

https://blog.csdn.net/qq_33416416/article/details/88870833

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

2019.4.10 在实际项目中发现ie浏览器(其他浏览器都没有问题)上传图片一直显示:正在上传请稍后:主要是参考了如下两篇文章:

https://blog.csdn.net/tonycc2012/article/details/8314758

https://www.cnblogs.com/fangwu/p/8370806.html

解决方法主要是:将 application/json 改为 text/plan

/*
	 * kingedu富文本获取前台输入数据
	 */
	@RequestMapping(value = "/inserKingedusImg",produces = MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
	@ResponseBody
	public String inserKingedusImg(@RequestParam(value = "myFileName") MultipartFile mf,
			HttpServletRequest request) throws ServletException, IOException {
		String realPath = request.getSession().getServletContext().getRealPath("myFileName");
		// 获取源文件
		String filename = mf.getOriginalFilename();
		String[] names = filename.split("\\.");//
		String tempNum = (int) (Math.random() * 100000) + "";
		String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];
		File targetFile = new File(realPath, uploadFileName);// 目标文件
		// 开始从源文件拷贝到目标文件
		// 传图片一步到位
		try {
			mf.transferTo(targetFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println(uploadFileName);
		map.put("error",0);// 这里应该是项目路径
		map.put("url", "http://192.168.137.149:8080/static/myFileName/" + uploadFileName);
		System.out.println(map.get("url"));
		return JSONUtils.toJSONString(map).toString();// 将图片地址返回(对象转换成json)
	}

重要:将 application/json 改为 text/plan

1.

2.

猜你喜欢

转载自blog.csdn.net/qq_33416416/article/details/88996382
今日推荐