说明
- CKeditor版本 ckeditor_4.7.3_standard
- Tomcat版本 apache-tomcat-8.0.44
下载CKeditor和CKeditor文档
- https://ckeditor.com/ckeditor-4/download/
- https://docs.ckeditor.com/ckeditor4/docs/#!/guide/dev_installation
- https://ckeditor.com/cke4/addons/plugins/all 插件下载
图片上传
下载好了!那么开始吧!
CKeditor默认把上传图片功能隐藏了,感觉好贱哦~
那么,他和我们躲猫猫,我们就把他找出来吧!
引用CKeditor
以下代码是官方给出 一切以官方为标准
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
引用正确后打开网页会看到CKeditor出来了!
为了上传图片,更改网页为jsp 这样我的Tomcat才可以发挥作用呀
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- 引用ckeditor JS文件 -->
<script src="ckeditor/ckeditor.js"></script>
<title>CKEditor</title>
</head>
<body>
<center>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="100">
文字在这!
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration. 官方代码有部分改动,比如这个宽高设置
CKEDITOR.replace( 'editor1',{ height: '240px', width: '520px' } );
</script>
</form>
</center>
</body>
</html>
修改配置文件 显示图片上传功能
修改image.js文件 文件所在位置: ckeditor/plugins/image/dialogs/image.js
打开后你会发现,我屮艸芔茻哦这是什么鬼,好咯,被压缩了…没关系呀,eclipse的ctrl+f搜索一下不就好了
1. 搜索Upload 搜到的第一个后面会有一个hidden:!0 把感叹号去掉,保存,刷新页面,你就会发现上传功能现身了
2. config.image_previewText||”这里是CKeditor中显示一大串英文的东西,把这里内容去掉用来显示图片”
3. 既然是上传文件当然得有行为咯 在ckeditor/config.js 在config.js 中增加一句:
//获取基地址
var location = (window.location+'').split('/');
var basePath = location[0]+'//'+location[2]+'/'+location[3];
config.filebrowserImageUploadUrl=basePath+"/upLoadFile.action";
意思为在上传图片的时候执行这个请求
行为接收upLoadFile.action的Servlet
文件上传用到了commons-fileupload
maven依赖
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
单纯的jar包下载地址 http://central.maven.org/maven2/commons-fileupload/commons-fileupload/1.3.2/commons-fileupload-1.3.2.jar
UpLoadFileServlet
文件上传思路与理解
1. 首先文件上传肯定不能上传到项目路径,因此我设置上传路径为项目部署路径上一级目录
2. 上传文件应该按照日期分类,以方便查看,不要为难自己嘛
3. 文件名,要么使用UUID,还是建议使用日期,以方便查看什么时候上传
4. 如果涉及多文件上传,那么保存的文件名不能重复,解决方案有,以时间命名精确到毫秒级别
上传图片需要显示在CKeditor中,那么CKeditor需要这些信息才能正确显示信息,所以需要回传一些数据给CKeditor
这是使用CKeditor上传图片发起的请求
//http://localhost:8080/CKEditor/upLoadFile.action?CKEditor=editor1&CKEditorFuncNum=0&langCode=zh-cn
String callback = req.getParameter("CKEditorFuncNum");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("<script type=\"text/javascript\">");
out.write("window.parent.CKEDITOR.tools.callFunction("+callback+",'"+weburl+fileName+"',''"+")");
out.write("</script>");
注意: CKeditor 4.7.3上传执行的参数发生了变化 详情请看代码
package com.yc.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpLoadFileServlet extends HttpServlet{
private String uploadPath = null;
private String filePath = "CKEditorPic";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//CKeditor上传文件的请求参数 CKEditor=editor1&CKEditorFuncNum=0&langCode=zh-cn
//http://localhost:8080/CKEditor/upLoadFile.action?CKEditor=editor1&CKEditorFuncNum=0&langCode=zh-cn
String type = "image";//req.getParameter("type"); 4.7.3版本无此参数
FileItemFactory itemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(itemFactory);
try {
FileItemIterator itemIterator = servletFileUpload.getItemIterator(req);
if (itemIterator.hasNext()) {
FileItemStream itemStream = itemIterator.next();
String name = itemStream.getName();
InputStream inputStream = itemStream.openStream();
String tagName = getTagName(name);
if ("image".equals(type)) { //allowedImages.contains(tagName) &&
String fileName = this.geneFileName(tagName);
Calendar c = Calendar.getInstance();
// 取tomcat路径 C:\apache-tomcat-8.0.44\webapps\CKEditor
String tomcatdir = req.getRealPath("/");
File tomcatFile = new File(tomcatdir);
// tomcatdir上一级路径 C:\apache-tomcat-8.0.44\webapps
File webapppath = tomcatFile.getParentFile();
// 生成文件路径
File picpath = new File(webapppath, filePath + File.separator + c.get(Calendar.YEAR) + File.separator
+ (c.get(Calendar.MONTH) + 1) + File.separator);
// 浏览器中CKeditor图片访问路径名
String weburl = "../"+filePath+"/" + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH) + 1) + "/";
// 判断目录是否存在,不在则创建
if (picpath.exists() == false) {
picpath.mkdirs();
}
//保存路径
uploadPath = picpath.toString();
//上传文件
this.upload(inputStream, fileName);
//返回数据给CKeditor
String callback = req.getParameter("CKEditorFuncNum");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("<script type=\"text/javascript\">");
out.write("window.parent.CKEDITOR.tools.callFunction("+callback+",'"+weburl+fileName+"',''"+")");
out.write("</script>");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
//获取上传文件的后缀名
private String getTagName(String fileName) {
int index = fileName.lastIndexOf(".")+1;
return fileName.substring(index);
}
//生成文件名 20171015210454919.png
private String geneFileName(String tagName) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
return sdf.format(new Date()) + "." + tagName;
}
//写入磁盘
private void upload(InputStream inputStream, String fileName) throws IOException {
File file = new File(uploadPath, fileName);
OutputStream os = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
inputStream.close();
os.close();
}
}
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
http://www.springmodules.org/schema/cache/springmodules-cache.xsd
http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>upLoadFileServlet</servlet-name>
<servlet-class>com.yc.servlets.UpLoadFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upLoadFileServlet</servlet-name>
<url-pattern>/upLoadFile.action</url-pattern>
</servlet-mapping>
</web-app>
好了,图片上传搞定
那么接下来,配置CKeditor吧 简化功能or增加功能
CKeditor配置
依然是修改配置文件ckeditor/config.js
直接看说明吧,我简化了配置,保留了几个小功能即可
/**
* CKEditor配置文件
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For complete reference see:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
//config.toolbarGroups 则不可以使用items 去掉Groups可自选items内容
config.toolbar = [
//提供复制张贴等 { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
//拼写检查等 { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
//链接 { name: 'links' },
{ name: 'insert', items: ['Image','HorizontalRule','SpecialChar','Smiley'] },
//插入 包括图片,表格'Table',水平线,特殊字符 表情'Smiley',分页符,'PageBreak
{ name: 'forms' },
{ name: 'tools', items: ['Maximize'] }, //工具 用于编辑器全屏
//包括源码等 { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
//加粗 倾斜 删除线等 { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
//有序 无序 引用等 { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
//输入文字风格 { name: 'styles' },
// { name: 'colors' },
//去掉? 关于功能 { name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
//工具栏的位置 设置编辑器功能位置 默认top bottom
config.toolbarLocation = 'top';
//当用户键入TAB时,编辑器走过的空格数,( ) 当值为0时,焦点将移出编辑框 如果不设置则无任何效果
config.tabSpaces = 4;
//工具栏默认是否展开
config.toolbarStartupExpanded = true;
//工具栏是否可以被收缩
config.toolbarCanCollapse = true;
//获取基地址
var location = (window.location+'').split('/');
var basePath = location[0]+'//'+location[2]+'/'+location[3];
//写action
config.filebrowserImageUploadUrl=basePath+"/upLoadFile.action";
};
好了,基本功能都OK了!
完整项目代码请移步百度网盘 链接:http://pan.baidu.com/s/1pLbrmx9 密码:5jas