(1)将CKeditor文件夹放入项目
(2)引入js文件
<script type="text/javascript" src="${pageContext.request.contextPath }/ckeditor/ckeditor.js"></script>
(3)创建文本域
<textarea name="noticeContent" id="noticeContent"></textarea>
(4)渲染ckeditor
var editor = null;
window.onload = function() {
editor = CKEDITOR.replace( 'noticeContent', {
customConfig:'${pageContext.servletContext.contextPath }/ckeditor/myconfig.js',
on: {
instanceReady: function( ev ) {
this.dataProcessor.writer.setRules( 'p', {
indent: false,
breakBeforeOpen: false, //<p>之前不加换行
breakAfterOpen: false, //<p>之后不加换行
breakBeforeClose: false, //</p>之前不加换行
breakAfterClose: false //</p>之后不加换行7
});
}
}
});
};
我这里加载的是自定义的myconfig.js配置文件,文件中可配置编辑器的一系列属性,其中比较重要的是config.filebrowserUploadUrl= “ckeditorUpload.htm”;这个属性定义了编辑器自带上传图片的上传路径。
CKEDITOR.editorConfig = function( config )
{
config.uiColor = '#ffffff';
config.font_names='宋体/SimSun;新宋体/NSimSun;仿宋_GB2312/FangSong_GB2312;楷体_GB2312/KaiTi_GB2312;黑体/SimHei;微软雅黑/Microsoft YaHei;'+ config.font_names;
config.language = 'zh-cn';
config.height = '600px';
config.filebrowserUploadUrl= "ckeditorUpload.htm";
config.toolbar = 'Basic';
config.toolbar = 'Full';
config.toolbar_Full = [
['Source','-','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
'/',
['Styles','Format','Font','FontSize'],
['TextColor','BGColor']
];
//工具栏是否可以被收缩
config.toolbarCanCollapse = true;
//工具栏的位置
config.toolbarLocation = 'top';//可选:bottom
//工具栏默认是否展开
config.toolbarStartupExpanded = true;
// 取消 “拖拽以改变尺寸”功能 plugins/resize/plugin.js
config.resize_enabled = true;
//清空图片上传预览框内的文字
config.image_previewText=' ';
};
(5)上传图片后台代码。图片上传后,回调ckeditor的callFunction函数,将编辑器自动传到后台的CKEditorFuncNum参数和图片路径回传给页面,配合服务器虚拟路径,完成编辑器中图片的回显。
@Autowired
private NoticeService noticeService;
@Value("#{configProperties['file_upload_path']}")
private String fileUploadPath;
@Value("#{configProperties['notice_info_image_file_upload_path']}")
private String noticeInfoImageFileUploadPath;
/**
* 插入图片
* @param request
* @param response
* @param upload
* @param uploadContentType
* @param uploadFileName
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping("/ckeditorUpload")
public void ckeditorUpload(HttpServletRequest request,HttpServletResponse response,MultipartFile upload,String uploadContentType,String uploadFileName ) throws IllegalStateException, IOException{
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
int i=upload.getOriginalFilename().lastIndexOf(".");
String substring = upload.getOriginalFilename().substring(i+1, upload.getOriginalFilename().length());
if(substring.equals("jpg")||substring.equals("bmp")||substring.equals("png")||substring.equals("gif")){
InputStream is = upload.getInputStream();
String FILEMAPPING = noticeInfoImageFileUploadPath;
String FILEPATH = fileUploadPath + FILEMAPPING;
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(1000);
String fileName = formatDate + random +"."+substring;
File filePath = new File(FILEPATH);
if(!filePath.exists()) filePath.mkdirs();
File toFile = new File(FILEPATH, fileName);
System.out.println(FILEPATH);
OutputStream os = new FileOutputStream(toFile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
String imageContextPath = "/fileUploadPath"+ FILEMAPPING + fileName;
String callback = request.getParameter("CKEditorFuncNum");
System.out.println(callback+","+imageContextPath);
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageContextPath + "',''" + ")");
out.println("</script>");
out.flush();
out.close();
}else{
response.setContentType("text/html;charset=UTF-8");
String callback = request.getParameter("CKEditorFuncNum");
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)');");
out.println("</script>");
out.flush();
out.close();
}
}
config.properties
file_upload_path = D\:\\WAYBILL\\fileUploadPath
notice_info_image_file_upload_path = /noticeInfoImg/
服务器虚拟路径
server.xml host标签内
<Context docBase="D:/WAYBILL/fileUploadPath/" path="/fileUploadPath/" reloadable="true"/>
数据库存储的图片路径
(6)页面效果