在項目中,要求所有的上傳文件都必須在項目運行目錄之外,所以在使用百度的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