因为要在网站上编辑富文本数据,所以直接采用百度的富文本编辑器,但是这个编辑器有个缺点,默认情况下,文件只能上传到网站的根目录,不能自定义路径。

而且json配置文件只能和controller.jsp在同一个目录下,不好管理。所以小淘气儿修改了部分源码以及配置了一个拦截器,实现了以上功能。

首先,将下载,并解压的文件夹复制到webapp目录下,如图:

并将ueditor/jsp/下的config.json移动到resources目录下,

config.json是配置图片,文件,视频信息的json格式的文件。以下我就用图片讲解:

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{ "uploadRoot": "F://javaWeb//UEditor/target/ueditor-1.0-SNAPSHOT/", /*文件上传根目录 */
/* 上传图片配置项 */
"imageActionName": "uploadimage", /* 执行上传图片的action名称 */
"imageFieldName": "upfile", /* 提交的图片表单名称 */
"imageMaxSize": 2048000, /* 上传大小限制,单位B */
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
"imageCompressEnable": true, /* 是否压缩图片,默认是true */
"imageCompressBorder": 1600, /* 图片压缩最长边限制 */
"imageInsertAlign": "none", /* 插入的图片浮动方式 */
"imageUrlPrefix": "http://localhost:8088/ueditor", /* 图片访问路径前缀 */
"imagePathFormat": "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
/* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
/* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
/* {time} 会替换成时间戳 */
/* {yyyy} 会替换成四位年份 */
/* {yy} 会替换成两位年份 */
/* {mm} 会替换成两位月份 */
/* {dd} 会替换成两位日期 */
/* {hh} 会替换成两位小时 */
/* {ii} 会替换成两位分钟 */
/* {ss} 会替换成两位秒 */
/* 非法字符 \ : * ? " < > | */
/* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */ /* 涂鸦图片上传配置项 */
"scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
"scrawlFieldName": "upfile", /* 提交的图片表单名称 */
"scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
"scrawlUrlPrefix": "", /* 图片访问路径前缀 */
"scrawlInsertAlign": "none", /* 截图工具上传 */
"snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
"snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
"snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */ /* 抓取远程图片配置 */
"catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
"catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
"catcherFieldName": "source", /* 提交的图片列表表单名称 */
"catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"catcherUrlPrefix": "", /* 图片访问路径前缀 */
"catcherMaxSize": 2048000, /* 上传大小限制,单位B */
"catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */ /* 上传视频配置 */
"videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
"videoFieldName": "upfile", /* 提交的视频表单名称 */
"videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"videoUrlPrefix": "", /* 视频访问路径前缀 */
"videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
"videoAllowFiles": [
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */ /* 上传文件配置 */
"fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
"fileFieldName": "upfile", /* 提交的文件表单名称 */
"filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"fileUrlPrefix": "", /* 文件访问路径前缀 */
"fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
"fileAllowFiles": [
".png", ".jpg", ".jpeg", ".gif", ".bmp",
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
], /* 上传文件格式显示 */ /* 列出指定目录下的图片 */
"imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
"imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
"imageManagerListSize": 20, /* 每次列出文件数量 */
"imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
"imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
"imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */ /* 列出指定目录下的文件 */
"fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
"fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
"fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
"fileManagerListSize": 20, /* 每次列出文件数量 */
"fileManagerAllowFiles": [
".png", ".jpg", ".jpeg", ".gif", ".bmp",
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
] /* 列出的文件类型 */ }

imageUrlPrefix+imagePathFormat是图片的访问路径,也是图片显示的关键。

uploadRoot是我新增加的键,对应的value是图片上传绝对路径。

正常情况下,在加载ueditor编辑器时,会访问ueditor/jsp/controller.jsp:

controller.jsp代码:

    request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
String rootPath = application.getRealPath( "/" );
System.out.println(rootPath);
out.write( new ActionEnter( request, rootPath ).exec() );

在这里解析的config.json,

在创建ActionEnter实例的时候,初始化ConfigManager类,其中ConfigManager类是关键。

百度源代码:

 //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package com.baidu.ueditor; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject; public final class ConfigManager {
private final String rootPath;//绝对根路径
private final String originalPath;
private final String contextPath;
private static final String configFileName = "config.json";
private String parentPath = null;//controller.jsp的上级目录路径
private JSONObject jsonConfig = null;//解析config.json后的json对象
private static final String SCRAWL_FILE_NAME = "scrawl";
private static final String REMOTE_FILE_NAME = "remote"; private ConfigManager(String rootPath, String contextPath, String uri) throws FileNotFoundException, IOException {
rootPath = rootPath.replace("\\", "/");
this.rootPath = rootPath;
this.contextPath = contextPath;
if(contextPath.length() > 0) {
this.originalPath = this.rootPath + uri.substring(contextPath.length());
} else {
this.originalPath = this.rootPath + uri;
} this.initEnv();
} public static ConfigManager getInstance(String rootPath, String contextPath, String uri) {
try {
return new ConfigManager(rootPath, contextPath, uri);
} catch (Exception var4) {
return null;
}
} public boolean valid() {
return this.jsonConfig != null;
} public JSONObject getAllConfig() {
return this.jsonConfig;
} public Map<String, Object> getConfig(int type) {
HashMap conf = new HashMap();
String savePath = null;
switch(type) {
case 1:
conf.put("isBase64", "false");
conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("imageMaxSize")));
conf.put("allowFiles", this.getArray("imageAllowFiles"));
conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
savePath = this.jsonConfig.getString("imagePathFormat");
break;
case 2:
conf.put("filename", "scrawl");
conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("scrawlMaxSize")));
conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
conf.put("isBase64", "true");
savePath = this.jsonConfig.getString("scrawlPathFormat");
break;
case 3:
conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("videoMaxSize")));
conf.put("allowFiles", this.getArray("videoAllowFiles"));
conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
savePath = this.jsonConfig.getString("videoPathFormat");
break;
case 4:
conf.put("isBase64", "false");
conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("fileMaxSize")));
conf.put("allowFiles", this.getArray("fileAllowFiles"));
conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
savePath = this.jsonConfig.getString("filePathFormat");
break;
case 5:
conf.put("filename", "remote");
conf.put("filter", this.getArray("catcherLocalDomain"));
conf.put("maxSize", Long.valueOf(this.jsonConfig.getLong("catcherMaxSize")));
conf.put("allowFiles", this.getArray("catcherAllowFiles"));
conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
savePath = this.jsonConfig.getString("catcherPathFormat");
break;
case 6:
conf.put("allowFiles", this.getArray("fileManagerAllowFiles"));
conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
conf.put("count", Integer.valueOf(this.jsonConfig.getInt("fileManagerListSize")));
break;
case 7:
conf.put("allowFiles", this.getArray("imageManagerAllowFiles"));
conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
conf.put("count", Integer.valueOf(this.jsonConfig.getInt("imageManagerListSize")));
} conf.put("savePath", savePath);
conf.put("rootPath", this.rootPath);
return conf;
} private void initEnv() throws FileNotFoundException, IOException {
File file = new File(this.originalPath);
if(!file.isAbsolute()) {
file = new File(file.getAbsolutePath());
} this.parentPath = file.getParent();
String configContent = this.readFile(this.getConfigPath()); try {
JSONObject e = new JSONObject(configContent);
this.jsonConfig = e;
} catch (Exception var4) {
this.jsonConfig = null;
} } private String getConfigPath() {
return this.parentPath + File.separator + "config.json";
} private String[] getArray(String key) {
JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
String[] result = new String[jsonArray.length()];
int i = 0; for(int len = jsonArray.length(); i < len; ++i) {
result[i] = jsonArray.getString(i);
} return result;
} private String readFile(String path) throws IOException {
StringBuilder builder = new StringBuilder(); try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
BufferedReader bfReader = new BufferedReader(reader);
String tmpContent = null; while((tmpContent = bfReader.readLine()) != null) {
builder.append(tmpContent);
} bfReader.close();
} catch (UnsupportedEncodingException var6) {
;
} return this.filter(builder.toString());
} private String filter(String input) {
return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
}
}

其中

    private String getConfigPath() {
return this.parentPath + File.separator + "config.json";
}

这方法是拼全config.json的绝对路径,但是parentPath是controller.jsp 的目录路径,所以限制config.json 必须和controller.jsp在同一个目录下。当用spring或者其他代替controller.jsp时,就会找不到这个json文件。

所以这个地方我直接改为

   //修改
private String getConfigPath() {
return this.rootPath + File.separator + "WEB-INF" + File.separator + "classes"+File.separator + "config.json";
}

当然这个地方您可以随意发挥。

再者,关于上传文件路径配置问题,在源码中下载图片的类是BinaryUploader,

 //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package com.baidu.ueditor.upload; import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
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; import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map; public class BinaryUploader {
public BinaryUploader() {
} public static final State save(HttpServletRequest request, Map<String, Object> conf) {
FileItemStream fileStream = null;
boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
if(!ServletFileUpload.isMultipartContent(request)) {
return new BaseState(false, 5);
} else {
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
if(isAjaxUpload) {
upload.setHeaderEncoding("UTF-8");
} try {
for(FileItemIterator e = upload.getItemIterator(request); e.hasNext(); fileStream = null) {
fileStream = e.next();
if(!fileStream.isFormField()) {
break;
}
} if(fileStream == null) {
return new BaseState(false, 7);
} else {
String savePath = (String)conf.get("savePath");
String originFileName = fileStream.getName();
String suffix = FileType.getSuffixByFilename(originFileName);
originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
savePath = savePath + suffix;
long maxSize = ((Long)conf.get("maxSize")).longValue();
if(!validType(suffix, (String[])conf.get("allowFiles"))) { return new BaseState(false, 8); } else { savePath = PathFormat.parse(savePath, originFileName);
String physicalPath = (String)conf.get("rootPath") + savePath;
InputStream is = fileStream.openStream();
State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
is.close();
if(storageState.isSuccess()) {
storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName + suffix);
}
return storageState;
}
}
} catch (FileUploadException var14) {
return new BaseState(false, 6);
} catch (IOException var15) {
return new BaseState(false, 4);
}
}
} private static boolean validType(String type, String[] allowTypes) {
List list = Arrays.asList(allowTypes);
return list.contains(type);
}
}

在第64行中,String physicalPath = (String)conf.get("rootPath") + savePath; 就是上传图片最后的路径。其中rootPath是根路径,savePath是自定义的图片保存路径(imagePathFormat对应的值),在源码中rootPath已被限制为网站根目录,所以在这里需要改变为自定义的路径。

其中ConfigManager类中第109,110这里传入的路径字符串,只需将这改为

   conf.put("savePath", savePath);
conf.put("rootPath", this.jsonConfig.getString("uploadRoot"));

就可以了。

最后,controller.jsp的替代方法:

利用拦截器:

 package com.imp.filter;

 import com.baidu.ueditor.ActionEnter;

 import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger; /**
* Created by (IMP)郑和明
* Date is 2016/12/26
*
* UEditor controller.jsp 拦截器
*
* 初始化 config,json
*
*/
@WebFilter(filterName = "UEditorFilter",urlPatterns = "/ueditor/jsp/controller.jsp")
public class UEditorFilter implements Filter {
private FilterConfig config; public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request= (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) resp;
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html");
String rootPath= config.getServletContext().getRealPath("/");
Logger.getLogger("imp").info(rootPath);
String res=new ActionEnter(request, rootPath).exec();
response.getWriter().write(res); }
public void init(FilterConfig config) throws ServletException {
this.config=config;
} }

或者

String mvc也可以(前提拦截所有jsp请求,然后自定义controller)(代码(略))

代码 github 地址  https://github.com/zhenghe1993/UEditor

关于百度Editor富文本编辑器 自定义上传位置的更多相关文章

  1. layui 魔改:富文本编辑器添加上传视频功能

    甲方又整新需求了:富文本编辑器需要可以传视频. layui本身的富文本编辑器没有传视频的功能,所以,又到了咱们魔改的时候了. 友情提醒,富文本编辑器 layedit 只有layui的V1版有,V2版没 ...

  2. bbs项目富文本编辑器实现上传文件到media目录

    media目录是在project的settings中设置的,static目录是django自己使用的静态文件的上传目录,media目录是用户自定义上传文件的目录 # Django用户上传的文件都放在m ...

  3. 给Django后台富文本编辑器添加上传文件的功能

    使用富文本编辑器上传的文件是要放到服务器上的,所以这是一个request.既然是一个request,就需要urls.py进行转发请求views.py进行处理.views.py处理完了返回一个文件所在的 ...

  4. Kindeditor JS 富文本编辑器图片上传指定路径

    js //================== KindEditor.ready(function (K) { var hotelid = $("#hotelid").val(); ...

  5. ASP.NET MVC5 中百度ueditor富文本编辑器的使用

    随着网站信息发布内容越来越多,越来越重视美观,富文本编辑就是不可缺少的了,众多编辑器比较后我选了百度的ueditor富文本编辑器. 百度ueditor富文本编辑器分为两种一种是完全版的ueditor, ...

  6. PHP如何搭建百度Ueditor富文本编辑器

    本文为大家分享了PHP搭建百度Ueditor富文本编辑器的方法,供大家参考,具体内容如下 下载UEditor 官网:下载地址 将下载好的文件解压到thinkphp项目中,本文是解压到PUBLIC目录下 ...

  7. 百度ueditor富文本编辑器的使用

    百度ueditor富文本编辑器的使用 //以下为我在官网下载的ueditor v1.3.5 php版的大楷配置步骤第一步: //配置文件的引入应该比功能文件先引入,最后设置语言类型.即:editor. ...

  8. django之百度Ueditor富文本编辑器后台集成

    Python3 + Django2.0 百度Ueditor 富文本编辑器的集成 百度富文本编辑器官网地址:http://fex.baidu.com/ueditor/ 疑问:为什么要二次集成? 答案:因 ...

  9. 百度Web富文本编辑器ueditor在ASP.NET MVC3项目中的使用说明

    ====================================================================== [百度Web富文本编辑器ueditor在ASP.NET M ...

随机推荐

  1. 8.Element-ui日期组件上传到后台日期少一天解决办法

    <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="转出日期& ...

  2. 原 史上最简单的SpringCloud教程 | 第八篇: 消息总线(Spring Cloud Bus)(Finchley版本)

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f8-bus/ 本文出自方志朋的博客 转载请标明出处: Spr ...

  3. Oracle书写格式

    字符串和日期要包含在单引号中 字符大小写敏感,日期格式敏感 默认日期格式:dd - MON - RR select * from emp where last_name = 'King' where ...

  4. 关于 NSData 的数据类型(2进制,16进制之间)及深入剖析(转)

    . NSData 与 NSString NSData-> NSString NSString *aString = [[NSString alloc initWithData:adataenco ...

  5. BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(模拟 调和级数)

    Time Limit: 3 Sec  Memory Limit: 64 MBSubmit: 3031  Solved: 1596[Submit][Status][Discuss] Descriptio ...

  6. chromium之tracked_objects

    // For each thread, we have a ThreadData that stores all tracking info generated // on this thread. ...

  7. 关于J2EE里面getContextPath()和getRealPath()的区别

    一直老搞不清楚这两个方法的区别,只知道他们都是拿来获取地址的.今天特意写了个小demo试了一下,代码如下: @Override protected void service(HttpServletRe ...

  8. 基于SpringBoot+SpringSecurity+mybatis+layui实现的一款权限系统

    这是一款适合初学者学习权限以及springBoot开发,mybatis综合操作的后台权限管理系统 其中设计到的数据查询有一对一,一对多,多对多,联合分步查询,充分利用mybatis的强大实现各种操作, ...

  9. 剑指offer—从头到尾打印链表

    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList. 递归添加...不为空就加 import java.util.ArrayList; public class Solution { pu ...

  10. linux服务基础之ftp服务

    ftp是一种文件传输协议,我们以redhat6.9为服务器系统,来介绍一下ftp服务器,这里我们先介绍一下ftp协议工作的原理 ftp协议可以在不同类型的计算机之间传输文件,工作流程大致为 1:客户机 ...