開發(fā)一個項目的時候,有一塊地方突然需要使用到富文本編輯器,之前也用過一些編輯器,例如wangEditor和百度的Editior,綜合來說,我更喜歡簡潔型的,wangEditor就非常不錯,簡潔大方。百度的Editior給人看起來有種太華麗的感覺,雖然都可以配置自己需要的使用插件,但是還是喜歡wangEditor。
今天這里要說到的是wangEditor和kindEditor。
首先來說:kindEditor
下載下來后解壓,解壓后重命名文件夾名稱為kindeditor。在Javaweb項目中如何使用,請看下圖配置:

說下總體的目錄結(jié)構(gòu):
- attached: 文件的上傳完的存儲目錄。
- examples: 例子。
- jsp: 上傳用到的文件。
- lang: 語言包。
- plugins: 配置插件包。
- themes: 主題目錄。
再下面的就是用到的主要js文件了。
項目運行的時候記得把這幾個包部署進去,包在lib目錄里面。

現(xiàn)在可以啟動tomcat,地址欄訪問:http://localhost/kindeditor/kindeditor/jsp/demo.jsp
如下圖是正確訪問以后出現(xiàn)的畫面:

選擇插入一張圖片,成功把上傳完的圖片顯示在文本編輯器里面

最后查看一下這個圖片所在的上傳目錄

kindeditor就說到這里,上傳都配置好了,后面的怎么獲取值就很好辦了,這里先不說了。直接下一個編輯器。
wangEditor的使用
首先,你進入到官網(wǎng),就感覺這個編輯器非常不錯,簡潔大方。看圖所示:

直接說在項目中如何使用吧?
復(fù)制到解壓后的文件到webapp目錄下

這里也是整體配置開始吧:
<!-- 創(chuàng)建一個編輯器 -->
<script type="text/javascript">
var E = window.wangEditor
var editor = new E('#editor')
/* 獲取元素 */
/* editor.customConfig.debug = location.href.indexOf('publishTask.html') > 0 */
// 限制一次最多上傳 5 張圖片
editor.customConfig.uploadImgMaxLength = 5
// 將圖片大小限制為 3M
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
/* 上傳圖片文件的參數(shù)名稱 */
editor.customConfig.uploadFileName = 'fileName'
editor.customConfig.uploadImgParams = {
//token: 'abcdef12345' // 屬性值會自動進行 encode ,此處無需 encode
}
/* 圖片上傳的配置 */
editor.customConfig.uploadImgServer = '/stt/file/savePicture' /* 上傳到服務(wù)器的,不能和base64同時使用 */
/* editor.customConfig.uploadImgShowBase64 = true */ /* base64存儲 */
/* 創(chuàng)建 */
editor.create();
/* 上傳監(jiān)聽函數(shù) */
editor.customConfig.uploadImgHooks = {
before: function (xhr, editor, files) {
// 圖片上傳之前觸發(fā)
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖片文件
alert(files)
},
success: function (xhr, editor, result) {
// 圖片上傳并返回結(jié)果,圖片插入成功之后觸發(fā)
console.log(xhr)
console.log(editor)
console.log(result)
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
},
fail: function (xhr, editor, result) {
// 圖片上傳并返回結(jié)果,但圖片插入錯誤時觸發(fā)
alert(result)
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
},
error: function (xhr, editor) {
// 圖片上傳出錯時觸發(fā)
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
},
timeout: function (xhr, editor) {
// 圖片上傳超時時觸發(fā)
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
},
// 如果服務(wù)器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置
// (但是,服務(wù)器端返回的必須是一個 JSON 格式字符串?。?!否則會報錯)
customInsert: function (insertImg, result, editor) {
// 圖片上傳并返回結(jié)果,自定義插入圖片的事件(而不是編輯器自動插入圖片?。。。? // insertImg 是插入圖片的函數(shù),editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
// 舉例:假如上傳圖片成功后,服務(wù)器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
var url = result.url
insertImg(url)
// result 必須是一個 JSON 格式字符串?。?!否則報錯
}
}
<!-- 獲取值 -->
document.getElementById('save').addEventListener('click', function () {
var content = editor.txt.text();
var title = $('input[name=title]').val();
var description = $('input[name=description]').val();
var score = $('input[name=score]').val();
if(title == '' || title == null){
alert('請輸入標題');
return false;
}
if(description == '' || description == null){
alert('請輸入任務(wù)簡述信息');
return false;
}
if(content =='' || content == null){
alert('請輸入內(nèi)容信息');
return false;
}
if(score =='' || score == null){
alert('請輸入積分設(shè)置數(shù)');
return false;
}else{
$('input[name=content]').val(content); //給隱藏表單域賦值
$.post('../../task/saveTask',$('form').serialize(),function(res){
alert(res)
});
}
}, false);
</script>
前端代碼粘貼到上面了,這里說上傳那塊兒的。
- 首先你的配置你的上傳服務(wù)器的請求地址.
- 對上傳按需做一些基本配置,如:同時上傳圖片的數(shù)量,大小限制,文件參數(shù)名稱等。
- 配置好上傳事件監(jiān)聽,成功了..失敗了...上傳圖片但圖片未返回報錯等等事件最好都監(jiān)聽一下。
- 返回格式的要求。官方提供了兩種。
第一種:
{
// errno 即錯誤代碼,0 表示沒有錯誤。
// 如果有錯誤,errno != 0,可通過下文中的監(jiān)聽函數(shù) fail 拿到該錯誤碼進行自定義處理
errno: 0,
// data 是一個數(shù)組,返回若干圖片的線上地址
data: [
'圖片1地址',
'圖片2地址',
'……'
]
}
第二種:
// 如果服務(wù)器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置
// (但是,服務(wù)器端返回的必須是一個 JSON 格式字符串!?。》駝t會報錯)
customInsert: function (insertImg, result, editor) {
// 圖片上傳并返回結(jié)果,自定義插入圖片的事件(而不是編輯器自動插入圖片?。。。? // insertImg 是插入圖片的函數(shù),editor 是編輯器對象,result 是服務(wù)器端返回的結(jié)果
//這里說的就是第二種的情況(但是感覺第二種只能單張圖傳,有點麻煩,第一種能多圖傳。)
// 舉例:假如上傳圖片成功后,服務(wù)器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
var url = result.url
insertImg(url)
// result 必須是一個 JSON 格式字符串?。?!否則報錯
}
}
好了,既然第一種要返回json格式,那就直接看后臺代碼吧。
這里是上傳的請求控制器
@ResponseBody
@RequestMapping(value="savePicture",method=RequestMethod.POST)
public JSONObject savePicture(@RequestParam("fileName") MultipartFile[] fileName,
HttpServletRequest request){
JSONObject obj = new JSONObject();
//測試上傳是否成功前寫死的例子
// String img[] = {"http://localhost/stt/file/image/1706231708000014/2017062317080001465502.jpg/true",
// "http://localhost/stt/file/image/1706211120000005/2017062111200000589174.jpg/true",
// "http://localhost/stt/file/image/1706191036000002/2017061910360000275916.png/true"};
try {
String[] img = saveImgFiles(fileName);
obj.put("errno", 0);
obj.put("data", img);
}catch (Exception e) {
obj.put("errno", -1);
obj.put("data", "上傳失敗!");
e.printStackTrace();
}
System.out.println(obj);
return obj;
}
再就是保存多張圖片的方法
/**
* 保存多張圖片
* @param product
* @param detailImgFiles
* @throws IOException
* @throws FileNotFoundException
*/
public String[] saveImgFiles(MultipartFile[] detailImgFiles) throws FileNotFoundException, IOException{
StringBuffer sb = new StringBuffer(50);
List<String> str = new ArrayList<>();
for (int i = 0; i < detailImgFiles.length; i++) {
MultipartFile file = detailImgFiles[i];
if("".equals(file.getOriginalFilename())){
continue;
}
// StringBufferUtil.append(sb,managerConf.getProductSave(),"/");
sb.append("/base/stt/img/");
FileUtil.createDirNotExists(sb.toString());
String newFileName = newFileName(file); //重命名文件
sb.append(newFileName);
str.add("/stt/file/image/" + newFileName +"/"); //訪問圖片輸出流的前綴地址 + //圖片存儲的物理路徑地址。
//保存文件
FileUtil.saveFile(detailImgFiles[i].getInputStream(), new FileOutputStream(sb.toString()));
StringBufferUtil.clear(sb);
}
String[] img = (String[])str.toArray(new String[str.size()]);
return img;
}
給文件重命名方法
/**
* 給文件重新命名
* @param minImgFile
* @return
*/
private static String newFileName(MultipartFile minImgFile){
String filename = minImgFile.getOriginalFilename();
String dateStr = DateUtil.getDateStr(new Date(), "yyyyMMddHHmmsssss");
StringBuffer sb = new StringBuffer(20);
sb.append(filename);
filename = sb.replace(0, filename.lastIndexOf("."),"").toString();
StringBufferUtil.clear(sb);
sb.append(dateStr);
for (int i = 0; i < 5; i++) {
sb.append( (int)(Math.random() * 10));
}
sb.append(filename);
return sb.toString();
}//end newFileName
還有一個地方需要注意的就是文件上傳到的是外部磁盤目錄,我們給返回的圖片要讓它訪問磁盤目錄文件,需要用文件輸出流:
/**
* 訪問一個添加的圖片
* @param fileName
* @param request
* @return
*/
@RequestMapping("/image/{fileName}/")
public void visitImg(@PathVariable("fileName") String fileName,HttpServletResponse response){
FileInputStream fis = null;
StringBuffer sb = new StringBuffer(20);
try {
// String imgPath = StringBufferUtil.append(sb, ManagerConf.getMangerConf().getProductSave(),"/",proNo,"/",fileName).toString();
sb.append("/base/stt/img/");
FileUtil.createDirNotExists(sb.toString());
String imgPath = sb.toString() + fileName;
if(!FileUtil.fileExists(imgPath)){
return;
}
ServletOutputStream os = response.getOutputStream();
fis = new FileInputStream(imgPath);
byte[] bs = new byte[fis.available()];
fis.read(bs);
os.write(bs);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fis != null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后,測試多圖同時上傳一下吧:

需要注意的地方,返回的json數(shù)據(jù)格式如下:
{"errno":0,"data":["/stt/file/image/2017062922410001580284.jpg/","/stt/file/image/2017062922410001546426.jpg/","/stt/file/image/2017062922410001522021.gif/"]}
errno為0是成功上傳完到后端后給前臺的提示,都需要返回給前端頁面。
這個弄清楚上傳的流程就好了,代碼這塊自己發(fā)揮下就行。
我的博客文章地址:http://www.hanyz.cn/2017/06/29/%E4%BB%8B%E7%BB%8D%E4%B8%A4%E7%A7%8D%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8/