在项目中,要求所有的上传文件都必须在项目运行目录之外,所以在使用百度的ueditor的时候上传配置实现自定义的路径,但是在网上搜了很多方法都没有实现,作者通过一片文章提及修改ueditor.jar的源码思路实现了上传自定义配置路径。下面是具体的方法。
1.重写ueditor的上传类。
如图中红框中的类都涉及部分修改。主要是对上传写入磁盘时的路径进行可配置的修改,改动较小。
public class UploadPathUtil {
private static String phyPath = null;
private static String virticalPath = null;
static {
Properties pro = getPropertiesByAbsolutePath("config.properties");
phyPath = pro.getProperty("filePath");
virticalPath = pro.getProperty("virticalPath");
}
public static Properties getPropertiesByAbsolutePath(String path) {
Properties pro = new Properties();
try {
URL url = new DefaultResourceLoader().getResource(path).getURL();
pro.load(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
return pro;
}
public static String getPhyPath(){
return phyPath;
}
public static String getVirticalPath(){
return virticalPath;
}
}
通过工具类获取项目配置的上传路径和虚拟路径。
public static State save(String content, Map<String, Object> conf) {
byte[] data = decode(content);
long maxSize = (Long)conf.get("maxSize");
if (!validSize(data, maxSize)) {
return new BaseState(false, 1);
} else {
String suffix = FileType.getSuffix("JPG");
String savePath = PathFormat.parse((String)conf.get("savePath"), (String)conf.get("filename"));
savePath = savePath + suffix;
//此处修改将ueditor读取的项目路径替换称配置的真实路径
String physicalPath = UploadPathUtil.getPhyPath()+savePath;
State storageState = StorageManager.saveBinaryFile(data, physicalPath);
if (storageState.isSuccess()) {
//这里需要返回给ueditor对应的虚拟路径,否则无法在前端显示
storageState.putInfo("url", UploadPathUtil.getVirticalPath()+PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", "");
}
return storageState;
}
}
2,前端配置修改,在ueditor/jsp/controller.jsp中修改方法为重写的方法。
request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
String rootPath = application.getRealPath( "/" );
//这里的UeditorActionEnter为重写的类
out.write( new UeditorActionEnter( request, rootPath ).exec() );
当然,config.json中改动不大,只修改imageUrlPrefix路径就可以,其他的保持不变。
/* 上传图片配置项 */
"imageActionName": "uploadimage", /* 执行上传图片的action名称 */
"imageFieldName": "upfile", /* 提交的图片表单名称 */
"imageMaxSize": 2048000, /* 上传大小限制,单位B */
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
"imageCompressEnable": true, /* 是否压缩图片,默认是true */
"imageCompressBorder": 1600, /* 图片压缩最长边限制 */
"imageInsertAlign": "none", /* 插入的图片浮动方式 */
"imageUrlPrefix": "http://localhost:8085/", /* 图片访问路径前缀 */
"imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
至此,自定义上传路径完成。
示例java代码:百度网盘,密码:4v2y