SSM+KindEditor实现富文本编辑器图片上传

场景

KindEitor官方文档:

http://kindeditor.net/demo.php

实现

效果

下载Kindeditor

下载地址:

http://kindeditor.net/down.php

点击最新版本或小面自己选择版本就可下载

下载之后解压

其中前面是各种语言的示例demo,主要部分是下面的lang、plugins、themes、kindeditor-all.js、kindeditor-all-min.js、license.txt

添加到项目

这里使用的是4.1.10版本

将解压后的核心文件夹复制到项目下webapp下的某目录下

 

修改jsp页面

打开jsp页面

首先引入kindeditor.js

<script type="text/javascript"
 src="${ctx}/resources/BJUI/plugins/kindeditor_4.1.10/kindeditor.js"></script>
<script type="text/javascript">

然后在页面需要添加富文本编辑器的地方添加textarea元素

<textarea name="content" id="content" class="j-content" rows="4"
							cols="58" data-toggle="kindeditor" data-minheight="500"
							style="width: 100%">
           					${message.content}
           				</textarea>

然后在页面上再添加脚本

<script type="text/javascript">
	var editor = null;
	KindEditor.create(
			'textarea[name="content"]',
			{
				uploadJson : '${ctx}/bus/pushMessageAction/doSaveImage',
				fillDescAfterUploadImage : false, //上传图片成功后转到属性页,为false则直接插入图片[设为true方便自定义函数(X_afterSelect)]
				items : [ 'source', '|', 'undo', 'redo', '|', 'preview',
						'print', 'template', 'cut', 'copy', 'paste',
						'plainpaste', 'wordpaste', '|', 'justifyleft',
						'justifycenter', 'justifyright', 'justifyfull',
						'insertorderedlist', 'insertunorderedlist', 'indent',
						'outdent', 'subscript', 'superscript', 'clearhtml',
						'quickformat', 'selectall', '|', 'fullscreen', '/',
						'formatblock', 'fontname', 'fontsize', '|',
						'forecolor', 'hilitecolor', 'bold', 'italic',
						'underline', 'strikethrough', 'lineheight',
						'removeformat', '|', 'table', 'hr', 'image' ],
				height : "400px",
				width :"80%",
				allowImageUpload : true,
				autoHeightMode : true,
				formatUploadUrl:false,
				afterCreate : function() {
					this.loadPlugin('autoheight');
				},
				afterBlur : function() {
					this.sync();
				}//Kindeditor下获取文本框信息  
				
			})
</script>

具体参数说明参照官方文档:

http://kindeditor.net/docs/option.html

编写后台接口

来到uploadJson 所对应的后台接口

@Description("图片保存")
 @ResponseBody
 @RequestMapping(value = "/doSaveImage")
 public void doSaveImage(HttpServletRequest request, HttpServletResponse response, MultipartFile imgFile,
   String dir) {
  
   String scheme = request.getScheme();//http
   String serverName = request.getServerName();//localhost
   int serverPort = request.getServerPort();//8080
   String contextPath = request.getContextPath();//项目名
   String url = scheme+"://"+serverName+":"+serverPort+contextPath+"/upload/messageImg";
  
 
  Map<String, Object> jsonResult = null;
  String msg = "";
  try {
   response.setCharacterEncoding("UTF-8");
   PrintWriter out = null;
   try {
    out = response.getWriter();
   } catch (IOException e1) {
    e1.printStackTrace();
   }
   String callback = request.getParameter("CKEditorFuncNum");

   // 获得response,request
   Map<String, Object> m = new HashMap<String, Object>();

   if (!ServletFileUpload.isMultipartContent(request)) {
    m.put("error", 1);
    m.put("message", "请选择文件!");
    out.print(getError("请选择文件。"));
    out.close();
    return;
   }

   String originalFileName = null;// 上传的图片文件名
   String fileExtensionName = null;// 上传图片的文件扩展名
   if (imgFile.getSize() > 2 * 1024 * 1024) {
     out.print(getError("上传文件大小超过限制。")); 
                 out.close(); 
                 return; 
   } else {
    originalFileName = imgFile.getOriginalFilename();
    System.out.println("上传的图片文件名=" + originalFileName);
    fileExtensionName = originalFileName
      .substring(originalFileName.lastIndexOf("."), originalFileName.length()).toLowerCase();
    System.out.println("图片文件扩展名=" + fileExtensionName);

    if (imgFile.getSize() != 0) {
     Map<String, Object> result = ImageUtil.getInstance().uploadImgByUuid(Constants.UPLOAD_IMG_MESSAGE,
       imgFile);
     if (result.get("statusCode") == "300") {
      //out.println("<script type=\"text/javascript\">");
      // out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'',"
      // + result.get("message") + ");");
      //returnKindEditorMsg(result.get("message").toString(), request, response);
      //out.println("</script>");
     }
     String s = (String) result.get("message");
     String s1 = s.replace('\\', '/');
     String imageUrl = url + "/"+s1;
     
       
                 JSONObject obj = new JSONObject();   
                 obj.put("error", 0);   
                 obj.put("url",imageUrl);   
                 out.print(obj.toJSONString()); 
                 out.close(); 
    }
   }
  } catch (Exception e) {
   msg = "接口调用异常";
   jsonResult = JsonResult.jsonValidateReturn(false, e.getMessage());
   LogService.getInstance(this).error("保存消息信息失败" + e.getMessage());
   /* return jsonResult; */
  }

 }

最终效果

点击上传图片按钮

上传之后

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值