1、首先引用ckeditor并且初始化,这里示例比较简单,也不加样式,版本为ckeditor4.11.4
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html lang="zh"> <head> <title>CKeditor</title> <script src="${pageContext.request.contextPath}/static/ckeditor_4.11.4/ckeditor.js"></script> </head> <body> <textarea name="editor" id="editor"></textarea> <script> CKEDITOR.replace('editor',{ filebrowserImageUploadUrl :"${pageContext.request.contextPath}/file/uploadImages.do?" }); </script> </body> </html>
在初始化CKeditor的时候filebrowserImageUploadUrl :"${pageContext.request.contextPath}/file/uploadImages.do?"这里填写处理图片上传的地方,最后的?加上表示支持直接粘贴自动上传,不加只能从图片中选择图片上传
接下来就是后台
package cc.acme_me.website.controller; import cc.acme_me.website.utils.PropertiesUtils; import cc.acme_me.website.utils.ResponseUtil; import cc.acme_me.website.utils.StringUtils; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/file") public class FileUploadController { @RequestMapping("/uploadImages") public String uploadImages(@RequestParam("upload") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws IOException { response.setContentType("text/html;charset=utf-8"); JSONObject jsonObject = new JSONObject(); try { if (file.isEmpty()) { jsonObject.put("uploaded", 0); Map<String, String> resultMap = new HashMap<>(); resultMap.put("message", "失败了"); jsonObject.put("error", resultMap); } else { String fileName = file.getOriginalFilename(); fileName = StringUtils.getUUID() + fileName.substring(fileName.lastIndexOf(".")); String path = request.getServletContext().getRealPath("/") + PropertiesUtils.getStringValue("imagePath"); FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(path + "/" + fileName))); jsonObject.put("uploaded", 1); jsonObject.put("url", "userImage/"+fileName); } } catch (Exception e) { e.printStackTrace(); } ResponseUtil.write(response, jsonObject); return null; } }
上传图片主要是注意一下json返回的数据
如果成功,返回的数据格式应该是{"uploaded":"1","url":"图片显示的路径"}
如果失败了,返回数据的格式应该是{"uploaded":"0","error":{"message":"上传失败信息"}}
接下来就可以看到演示效果了
当然,也支持图片粘贴上传