spring boot 、springMVC環境整合百度ueditor富文字編輯器,使用七牛雲端儲存圖片
基於spring boot的專案中要用到富文字編輯器,但百度UEditor的後臺程式碼給出的是jsp版本的實現,由於專案使用的thymeleaf,不願為了一個外掛單獨新增jsp支援;且專案中又使用七牛儲存圖片等檔案,便重寫UEditor的後臺程式碼。
原料:
特點:
基於spring boot、spirngMVC環境,整合百度UEditor和七牛儲存
重寫了儲存圖片的程式碼邏輯
整合七牛sdk,支援不同區域伺服器
修改了多圖上傳彈框的圖片列表相關js的程式碼
將UEditor的config.json配置化
內建springMVC上傳介面
在spring boot環境中,只需引入jar,配置檔案中新增config.json配置及七牛相關配置即可使用。
修改記錄:
1、上傳介面:
@Controller
@RequestMapping("/ueditor")
public class UeditorController {
@Autowired
private ActionEnter actionEnter;
@ResponseBody
@RequestMapping("/upload")
public String exe(HttpServletRequest request){
return actionEnter.exec(request);
}
}
修改 ueditor.config.js 的serverUrl引數,匹配後臺介面;這裡使用的絕對路徑,可根據專案情況修改。
serverUrl: “/ueditor/upload”
2、基於spring boot配置:
@ConfigurationProperties(prefix = "ueditor")
public class UeditorProperties {
private String config = "{}";
private String accessKey;
private String secretKey;
//七牛機房 華東:zone0 華北:zone1 華南:zone2 北美:zoneNa0
private String zone = "autoZone" ;
private String bucket;
private String baseUrl;
private String uploadDirPrefix = "ueditor/file/";
//......
}
3、重寫StorageManager類,只使用七牛上傳圖片,去除了舊程式碼儲存到本地的功能。
public static String accessKey;
public static String secretKey;
public static String baseUrl;
public static String bucket;
public static String uploadDirPrefix;
public static Zone zone;
public static State saveBinaryFile(byte[] data, String path) {
State state = null ;
String key = uploadDirPrefix + getFileName(path);
try {
String uploadToken = Auth.create(accessKey, secretKey).uploadToken(bucket);
Response response = new UploadManager(new Configuration(zone)).put(data, key, uploadToken);
if (response.statusCode == 200) {
state = new BaseState(true);
state.putInfo("size", data.length);
state.putInfo("title", path);
state.putInfo("url", baseUrl + key);
} else {
state = new BaseState(false, AppInfo.IO_ERROR);
}
} catch (QiniuException e) {
state = new BaseState(false, AppInfo.IO_ERROR);
}
return state;
}
//...
private static State saveTmpFile(File tmpFile, String path) {
State state = null ;
String key = uploadDirPrefix + getFileName(path);
try {
String uploadToken = Auth.create(accessKey, secretKey).uploadToken(bucket);
Response response = new UploadManager(new Configuration(zone)).put(tmpFile, key, uploadToken);
if (response.statusCode == 200) {
state = new BaseState(true);
state.putInfo("size", tmpFile.length());
state.putInfo("title", key);
state.putInfo("url", baseUrl +"/"+ key);
} else {
state = new BaseState(false, AppInfo.IO_ERROR);
}
} catch (QiniuException e) {
state = new BaseState(false, AppInfo.IO_ERROR);
}
return state;
}
4、重寫多個類ImageHunter、ActionEnter、FileManager等
5、修改ueditor/dialogs/image/image.js的857行getImageData()方法,此方法是向後臺拉取圖片列表資料;為了能分頁,需要迎合七牛的sdk規範,此處添加了引數:marker ;相對應,後臺的FileManager類listFile方法也做了修改。
/* 初始化第一次的資料 */
initData: function () {
/* 拉取資料需要使用的值 */
this.state = 0;
this.listSize = editor.getOpt('imageManagerListSize');
this.listIndex = 0;
this.listEnd = false;
this.marker = undefined;
/* 第一次拉取資料 */
this.getImageData();
},
//......
/* 向後臺拉取圖片列表資料 */
getImageData: function () {
var _this = this;
if(!_this.listEnd && !this.isLoadingData) {
this.isLoadingData = true;
var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
isJsonp = utils.isCrossDomainUrl(url);
ajax.request(url, {
'timeout': 100000,
'dataType': isJsonp ? 'jsonp':'',
'data': utils.extend({
start: this.listIndex,
size: this.listSize,
marker:this.marker
}, editor.queryCommandValue('serverparam')),
'method': 'get',
'onsuccess': function (r) {
try {
var json = isJsonp ? r:eval('(' + r.responseText + ')');
if (json.state == 'SUCCESS') {
_this.pushData(json.list);
_this.listIndex = parseInt(json.start) + parseInt(json.list.length);
_this.marker = json.marker;
if(_this.listIndex >= json.total) {
_this.listEnd = true;
}
if("true"==json.isLast){
_this.listEnd = true;
}
_this.isLoadingData = false;
}
} catch (e) {
if(r.responseText.indexOf('ue_separate_ue') != -1) {
var list = r.responseText.split(r.responseText);
_this.pushData(list);
_this.listIndex = parseInt(list.length);
_this.listEnd = true;
_this.isLoadingData = false;
}
}
},
'onerror': function () {
_this.isLoadingData = false;
}
});
}
},
使用:
1、引入jar (原始碼在github,請自行編譯後再引入):
<!--注意:此版本與上個版本maven座標不同,-->
<dependency>
<groupId>com.zrk1000</groupId>
<artifactId>spring-boot-mvc-ueditor-qiniu</artifactId>
<version>ueditor1.4.3.3-qiniu7.2.X</version>
</dependency>
2、spring boot啟動類新增掃描: @ComponentScan(basePackages = {“com.baidu”}):
@Controller
@ComponentScan(basePackages = {"com.zrk","com.baidu"})
@SpringBootApplication
public class SpringBootMvcUeditorQiniuDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMvcUeditorQiniuDemoApplication.class, args);
}
@RequestMapping("/")
public String index(){
return "ueditor";
}
}
3、application.properties中新增ueditor的config.json配置,和七牛相關配置:
spring.thymeleaf.enabled=true
spring.http.multipart.max-file-size=500MB
spring.http.multipart.max-request-size=20MB
ueditor.config={"imageActionName":"uploadimage","imageFieldName":"upfile","imageMaxSize":2048000,"imageAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"imageCompressEnable":true,"imageCompressBorder":1600,"imageInsertAlign":"none","imageUrlPrefix":"","imagePathFormat":"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","scrawlActionName":"uploadscrawl","scrawlFieldName":"upfile","scrawlPathFormat":"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","scrawlMaxSize":2048000,"scrawlUrlPrefix":"","scrawlInsertAlign":"none","snapscreenActionName":"uploadimage","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","catcherFieldName":"source","catcherPathFormat":"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}","catcherUrlPrefix":"","catcherMaxSize":2048000,"catcherAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"videoActionName":"uploadvideo","videoFieldName":"upfile","videoPathFormat":"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}","videoUrlPrefix":"","videoMaxSize":102400000,"videoAllowFiles":[".flv",".swf",".mkv",".avi",".rm",".rmvb",".mpeg",".mpg",".ogg",".ogv",".mov",".wmv",".mp4",".webm",".mp3",".wav",".mid"],"fileActionName":"uploadfile","fileFieldName":"upfile","filePathFormat":"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}","fileUrlPrefix":"","fileMaxSize":51200000,"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","imageManagerListPath":"/ueditor/jsp/upload/image/","imageManagerListSize":20,"imageManagerUrlPrefix":"","imageManagerInsertAlign":"none","imageManagerAllowFiles":[".png",".jpg",".jpeg",".gif",".bmp"],"fileManagerActionName":"listfile","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"]}
ueditor.access-key=8nU0zA9aTvfHBZs0fPZZWd8gpnFRtOkOPkiTB6M0
ueditor.secret-key=400iGAeaeJyjgSm26-wT8R-HQYZbBR1el_cDiRIq
#七牛機房 華東:zone0 華北:zone1 華南:zone2 北美:zoneNa0
# ueditor.zone也可不配置,會自動識別區域
ueditor.zone=zone0
#zrk-test 華東
ueditor.bucket=zrk-test
ueditor.base-url=http://od710rrnd.bkt.clouddn.com
#zrk-test-huabei 華北
#ueditor.bucket=zrk-test-huabei
#ueditor.base-url=http://ordwj6hok.bkt.clouddn.com
ueditor.upload-dir-prefix=biz/img/