進入ueditor官網下載JSP版本插件,地址:點擊打開鏈接
放入到項目相應位置,無需修改裏面任何配置,結構如圖:
jsp頁面代碼:
<div id="myEditor"></div>
js引用代碼:
var item = {
toolbars: [
['fullscreen', 'undo', 'redo', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat ', 'simpleupload', 'insertvideo', 'lineheight','inserttable','|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify'],
['formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', 'fontfamily','fontsize']
],
autoHeightEnabled: true, //是否自動長高,默認true
autoFloatEnabled: false, //是否保持toolbar的位置不動,默認true
wordCount: true, //是否開啓字數統計 默認true
maximumWords: 100000, //允許的最大字符數 默認值:10000
wordOverFlowMsg: "<span style='color:red'>超出範圍了!!!!!!!!</span>", //超出字數限制提示
elementPathEnabled: false, //是否啓用元素路徑
padding: 0,
saveInterval: 5000000, // 將其設置大點,模擬去掉自動保存功能
allowDivTransToP: false
};
//傳參生成實例
ue = UE.getEditor('myEditor', item);
按照上面操作,到這裏已經可以使用Ueditor了,但是圖片、視頻的上傳功能還是不能用,代碼會報錯,這時候只需要在上面js後面加上一段js配置,代碼如下:
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadvideo') {
return '${ctx}/manage/attach/uploadFile.do';
} else {
return this._bkGetActionUrl.call(this, action);
}
}
其中第一個return是後臺上傳接口,第二個return是Ueditor自帶接口。配置好了,上傳圖片或視頻的時候,會進入到後臺上傳接口做相應操作,我的後臺接口代碼:/**
* uploadFile:ueditor上傳附件. <br/>
* @author lcma
* @param model Model
* @param file MultipartFile
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return
* @throws Exception
* @since JDK 1.6
*/
@RequestMapping(value="/uploadFile.do")
public RequestResultBean uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request,HttpServletResponse response){
//返回對象
RequestResultBean result = new RequestResultBean();
Attachment attach = new Attachment();
//獲取用戶信息
User user = WebUtils.getUserInfo(request);
//獲取文件保存後面的動態路徑
String backPath = this.getPath();
//文件保存的完整路徑
String path = ResourceBean.HEAD_PATH + backPath;
//獲取文件名
String fileName = file.getOriginalFilename();
//獲取轉換後的uuid文件名
String UuidFileName = this.getUUIDFileName(fileName);
//完善附件對象信息
attach.setCreateTime(new Date());
attach.setSize(file.getSize());
attach.setName(fileName);
attach.setExt(this.getExtName(fileName, '.'));
attach.setRealPath(backPath + "/" + UuidFileName);
attach.setCreateUser(user);
this.checkFileType(attach, fileName);
File targetFile = new File(path, UuidFileName);
//創建文件夾
if(!targetFile.exists()){
targetFile.mkdirs();
}
Map<String,String> map = new HashMap<String,String>();
try {
//上傳附件
file.transferTo(targetFile);
//保存附件信息
attachmentService.save(attach);
map.put("state", "SUCCESS");
map.put("url", ResourceBean.DOWNLOAD_URL + attach.getId());
map.put("title", "");
map.put("original","");
} catch (Exception e) {
LOGGER.error("upload error:", e);
map.put("state", "上傳失敗");
}
try {
response.setCharacterEncoding("GBK");
response.getWriter().write(JacksonUtil.toJSon(map)); //因爲上傳不能使用@ResponseBody,因此用原生的response來傳值到前臺。
} catch (IOException e) {
LOGGER.error("upload error:", e);
return result;
}
return null;
}
上面代碼中的ResourceBean.HEAD_PATH和ResourceBean.DOWNLOAD_URL是我配置在properties配置文件中的,通過spring讀取配置文件中的數據,如讀取配置暫時不會,可以先將者兩個屬性在代碼中寫死。
ResourceBean.HEAD_PATH表示的意思是上傳文件存儲的路徑,例如“D:file\”,我這裏存儲上傳文件的文件夾的格式是HEAD_PATH + 2016/5/23(日期),uuid替換文件名,防止文件名稱重複。
ResourceBean.DOWNLOAD_URL代表的意思是下載方法的路徑,也就是下面代碼中download方法的路徑,文件上傳成功後,會返回download方法和該文件的id到ueditor編輯框中,編輯框會自動請求該url(下面的download方法),download方法通過文件的id找到文件存在本地的路徑,返回文件流到編輯框中,自動生成圖片或視頻。
上傳成功後,使用map集合返回參數(Ueditor默認使用map接收),url參數返回的是顯示在編輯框裏面的圖片下載地址。我的寫法是,下載地址請求後臺,後臺在數據庫中查找出附件上傳的地址,轉成流的形式在編輯框中顯示(視頻也是一樣)。代碼如下:
/**
* download:附件下載. <br/>
* @author lcma
* @param response
* @param id
* @throws IOException
* @since JDK 1.7
*/
@RequestMapping("/download.do")
public void download(HttpServletResponse response, String id) throws IOException {
if(StringUtils.hasText(id)){
Attachment attach = attachmentService.getById(id);
response.reset();
response.addHeader("Content-Disposition", "attachment;filename="+new String(attach.getName().getBytes("gbk"),"iso-8859-1")); //轉碼之後下載的文件名不會出現中文亂碼
response.addHeader("Content-Length", "" + attach.getSize());
response.setContentType("application/octet-stream;charset=UTF-8");
String path = ResourceBean.HEAD_PATH + attach.getRealPath();
//讀取文件
InputStream in = new FileInputStream(path);
OutputStream out = response.getOutputStream();
//寫文件
int b;
while((b=in.read())!= -1){
out.write(b);
}
in.close();
out.close();
}
}
PS:本篇文章處理上傳文件的方式並是將上傳的文件存儲在本地,並且將文件的相關屬性保存在數據庫表中(主鍵id、文件名稱、文件大小、文件類型、文件存儲地址、上傳時間等)。這樣設計的好處就是在下載的時候只需要在知道該文件在表中對應的主鍵id即可,通過id查找到對應的文件地址,返回流文件,避免了直接將文件的存儲地址暴露在客戶端,提高了系統的安全性。
上傳下載方法中,公共方法貼出來,方便以後查看:
/**
* 獲取保存附件路徑,年/月/日
*/
private String getPath(){
//獲取年月日
Calendar a=Calendar.getInstance();
String year = String.valueOf(a.get(Calendar.YEAR));
String month = String.valueOf(a.get(Calendar.MONTH)+1);
String day = String.valueOf(a.get(Calendar.DAY_OF_MONTH));
StringBuilder backPath = new StringBuilder(128);
backPath.append(year).append("/").append(month).append("/").append(day);
return backPath.toString();
}
/**
* getExtName:獲取文件後綴名. <br/>
* @author lcma
* @param s 文件名包括後綴
* @param split 文件名和後綴之間的‘.’
* @return
* @since JDK 1.7
*/
private String getExtName(String s, char split) {
int i = s.lastIndexOf(split);
int leg = s.length();
return i > 0 ? (i + 1) == leg ? " " : s.substring(i+1, s.length()) : " ";
}
/**
* getUUIDFileName:把文件名轉換成uuid表示,防止文件名上傳重複. <br/>
* @author lcma
* @param fileName 文件名
* @return
* @since JDK 1.6
*/
private String getUUIDFileName(String fileName){
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder(100);
sb.append(uuid.toString()).append(".").append(this.getExtName(fileName, '.'));
return sb.toString();
}
/**
* checkFileType:判斷附件格式類型. <br/>
* @author lcma
* @param attach 附件對象
* @param fileName 文件名
* @since JDK 1.6
*/
private void checkFileType(Attachment attach, String fileName){
String type = this.getExtName(fileName, '.').toLowerCase();
if(VEDIO_FORMAT.equals(type)){
attach.setMediaType(MediaType.SP);
}else{
attach.setMediaType(MediaType.TP);
}
}
上傳一張實例圖片,哈哈:
獲取編輯框內容:
ue.getContent();
賦值給編輯框:
ue.setContent(content);