背景介绍,之前项目一直使用kindeditor富文本,客户反应不好用要求升级,看到了WangEditor这款轻量级编辑器,直接使用源码修改完成上传。
<div class="xxx" id="contentsd">
</div>
<input type="hidden" id="addContent" name="addContent"/>
<script type="text/javascript" src="${webResourceUrl}/wangEditor/release/wangEditor.min.js"></script>
<script type="text/javascript">
const ES = window.wangEditor;
const editor = new ES('#contentsd');
editor.config.menus =[
'head', // 标题
'bold', // 粗体
'fontSize', // 字号
'fontName', // 字体
'italic', // 斜体
'underline', // 下划线
'strikeThrough', // 删除线
'foreColor', // 文字颜色
'backColor', // 背景颜色
'link', // 插入链接
'list', // 列表
'justify', // 对齐方式
'quote', // 引用
'emoticon', // 表情
'image', // 插入图片
// 'table', // 表格
// 'video', // 插入视频
'code', // 插入代码
'undo', // 撤销
'redo' // 重复
];
editor.config.zIndex = 500;
editor.config.placeholder = '请在此输入知识内容';
editor.config.focus = false;
editor.config.debug=true;
// 隐藏“网络图片”tab
editor.config.showLinkImg = false;
// 关闭粘贴内容中的样式
editor.config.pasteFilterStyle = false;
// 忽略粘贴内容中的图片
editor.config.pasteIgnoreImg = true;
//上传图片时,可自定义filename(controller层需要设置传入的名字时保持一致)
editor.config.uploadFileName = 'myFile';
// 配置服务器端地址 upload:上传图片地址(调用controller层接口)
editor.config.uploadImgServer='${ctx}/r/plugins/kindeditor/jsp/upload_json.jsp?infoPath='+today;
// 将图片大小限制为 3M
editor.config.uploadImgMaxSize = 3 * 1024 * 1024;
// 一次最多上传图片的数量
editor.config.uploadImgMaxLength = 10;
//可使用监听函数在上传图片的不同阶段做相应处理
editor.config.uploadImgHooks = {
before: function (xhr, editor, files) {
// 图片上传之前触发
// return {
// prevent: true,
// msg: '放弃上传'
// }
console.log(xhr);
// return {
// prevent: true,
// msg: '放弃上传'
// }
},
success: function (xhr, editor, result) {
// 图片上传并返回结果,图片插入成功之后触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
console.log('success', xhr)
},
fail: function (xhr, editor, result) {
// 图片上传并返回结果,但图片插入错误时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
console.log('fail', resData);
},
error: function (xhr, editor) {
// 图片上传出错时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
console.log('error', xhr, resData);
},
timeout: function (xhr, editor) {
// 图片上传超时时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
console.log('timeout')
},
// 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
// (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
customInsert: function (insertImg, result, editor) {
//这个是用来回显的
// 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
// insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
// 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
//data是我后台返回的图片调用地址:url
console.log('customInsert', result);
var urls = result.url;
insertImg(urls)
// result 必须是一个 JSON 格式字符串!!!否则报错
}
}
editor.create();
</script>
下面是JSP上传代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.json.simple.*" %>
<%@ page import="com.common.util.FtpUtil" %>
<%@page import="com.eshop.core.constant.FTPConstant"%>
<%
//文件保存目录路径
String savePath = pageContext.getServletContext().getRealPath("/uploadFile") + "/editor/";
//文件保存目录URL
String saveUrl = request.getContextPath() + "/uploadFile/editor/";
System.out.println("savePath ="+savePath);
System.out.println("saveUrl ="+saveUrl);
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
//最大文件大小
long maxSize = 1000000;
response.setContentType("text/html; charset=UTF-8");
if(!ServletFileUpload.isMultipartContent(request)){
out.println(getError("请选择文件。"));
return;
}
//检查目录
File uploadDir = new File(savePath);
String dirName = "image";
//创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
System.out.println("fileName ="+fileName);
long fileSize = item.getSize();
if (!item.isFormField()) {
System.out.println("item.getSize() ="+item.getSize());
//检查文件大小
if(item.getSize() > maxSize){
out.println(getError("上传文件大小超过限制。"));
return;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try{
InputStream ins = item.getInputStream(); //获得上传图片的流
String infoPath = request.getParameter("infoPath"); //获得保存路径
if(infoPath==null){//如果获得的路径为null 则默认路径为“upload”
infoPath = "upload";
}
FtpUtil ftpUtil=new FtpUtil();
ftpUtil.store(infoPath+newFileName, ins); //上传到ftp服务器
String url = FTPConstant.url; //获得ftp的Url
System.out.println("url ="+url);
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", url+infoPath+newFileName);
System.out.println("url ="+url+infoPath+newFileName);
out.println(obj.toJSONString());
}catch(Exception e){
out.println(getError("上传文件失败。"));
return;
}
}
}
%>
<%!
private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toJSONString();
}
%>