wangEditor3上傳圖片到服務(wù)器以及刪除服務(wù)器多余的圖片(包括wangEditor3內(nèi)容處理以及圖片上傳和刪除)

1、內(nèi)容處理

1.1 設(shè)置內(nèi)容 ?

? ? ? ? 添加內(nèi)容的方式有三種:第一種是直接將內(nèi)容寫到要?jiǎng)?chuàng)建編輯器的<div>標(biāo)簽中,第二種是在創(chuàng)建編輯器之后,使用editor.txt.html(...)設(shè)置編輯器內(nèi)容,第三種是在創(chuàng)建編輯器之后,使用editor.txt.append('<p>追加的內(nèi)容</p>')繼續(xù)追加內(nèi)容。

? ? ? ? 清空內(nèi)容可以使用editor.txt.clear()

1.2 獲取內(nèi)容

? ? ? ?? 獲取內(nèi)容的方式有三種:第一種是使用editor.txt.html()讀取文本的html代碼,第二種是使用editor.txt.text()獲取純文本內(nèi)容,第三種是使用editor.txt.getJSON()獲取 JSON 格式的編輯器的內(nèi)容。

? ? ? ? ? 需要注意的是:從編輯器中獲取的 html 代碼是不包含任何樣式的純 html,如果顯示的時(shí)候需要對(duì)其中的<table><code><blockquote>等標(biāo)簽進(jìn)行自定義樣式(這樣既可實(shí)現(xiàn)多皮膚功能)。

1.3 使用textarea?

? ? ? ? wangEditor 從v3版本開始不支持 textarea ,但是可以通過onchange來實(shí)現(xiàn) textarea 中提交富文本內(nèi)容。

2、上傳圖片

? ??默認(rèn)情況下,編輯器不會(huì)顯示“上傳圖片”的tab,因?yàn)槟氵€沒有配置上傳圖片的信息。有兩種方式可以實(shí)現(xiàn)顯示“上傳圖片”的tab,一是在編輯器創(chuàng)建之前添加editor.customConfig. uploadImgShowBase64 = true,使用 base64 保存圖片;二是在編輯器創(chuàng)建之前添加editor.custom Config.uploadImgServer = '/upload',上傳圖片到服務(wù)器。

? ? 默認(rèn)情況下,“網(wǎng)絡(luò)圖片”tab是一直存在的。如果不需要,可以在編輯器創(chuàng)建之前添加editor.customConfig.showLinkImg = false,隱藏“網(wǎng)絡(luò)圖片”tab。

2.1? 上傳圖片到服務(wù)器

? ? ? ? 由于使用base64保存圖片上傳和文本提交沒有多大的區(qū)別,所以我這里就不贅述。不懂而又想了解的可以點(diǎn)擊這里進(jìn)入它的官方文檔。

? ? ?? 這里我重點(diǎn)介紹使用自定義上傳圖片事件上傳圖片至服務(wù)器和刪除服務(wù)器多余的圖片。

代碼示例如下:

index.jsp文件:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>富文本</title>

<link type="text/css" href="css/wangEditor-fullscreen-plugin.css" rel="stylesheet">

</head>

<body>

<form>

<input type="hidden" value="" id="id" name="id"/>

新聞標(biāo)題:<input type="text" id="title" name="title"/><br>

新聞內(nèi)容:

<textarea id="text1" hidden style="width:100%;height:200px;"></textarea>

<div id="div1"></div>

<input type="submit"? value="提交" id="submit" name="submit"/>

</form>

<input type="button" id="HTML" value="提交HTML"/>

<input type="button" id="TEXT" value="提交TEXT"/>

<input type="button" id="JSON" value="提交JSON"/>

<script? src="js/wangEditor.js" type="text/javascript"></script>

<script src="js/wangEditor-fullscreen-plugin.js"></script>

<script src="js/jquery.js" type="text/javascript" ></script>

<script type="text/javascript">

$(function () {

//獲得數(shù)據(jù)庫中新聞數(shù)目并賦值給隱藏域

$.ajax({

url:"translate/Servlet",

type:"POST",

data:"opr=count",

dataType:"json",

success:function (da) {

$("#id").val(parseInt(da)+1);

},

error:function () {

alert("統(tǒng)計(jì)出錯(cuò),請(qǐng)重新嘗試或聯(lián)系管理人員!");

}

});

});

</script>

<script type="text/javascript">

var E =window.wangEditor

? var editor =new E('#div1');

var $text1 =$('#text1');

// 禁用編輯功能

/*? editor.$textElem.attr('contenteditable', false);*/

/*? editor.customConfig.uploadImgTimeout = 3000*/

//自定義上傳圖片事件,將圖片上傳到服務(wù)器

? editor.customConfig.customUploadImg =function(files,insert) {

var formData =new FormData();

for(var i =0;i < files.length;i ++) {

formData.append("files[" +i +"]", files[i],files[i].name);

}

$.ajax({

url:'wangedit/upload?id='+$("#id").val(),//這里是個(gè)servlet

? ? ? type:"POST",

data:formData,

async:false,

cache:false,

contentType:false,

processData:false,

success:function(da){

console.log(da.data[j]);

if(da.errno ==0){

for(var j=0;j

insert(da.data[j]);

}

}else{

alert(da.msg);

return;

}

}

});

};

// 將圖片大小限制為 3M

? editor.customConfig.uploadImgMaxSize =3 *1024 *1024;

/*editor.customConfig.uploadImgTimeout = 5000000;*/

// 限制一次最多上傳 5 張圖片

? editor.customConfig.uploadImgMaxLength =30;

// 或者 var editor = new E( document.getElementById('editor') )

? editor.customConfig.onchange =function (html) {

// 監(jiān)控變化,同步更新到 textarea

? ? $text1.val(html)

}

editor.create();

//全屏初始化

? E.fullscreen.init('#div1');

// 初始化 textarea 的值

? $text1.val(editor.txt.html());

//單擊獲取HTML代碼

$("#HTML").click(function(){

var content=editor.txt.html();

console.log(content);

alert(content);

})

//單擊獲取文本內(nèi)容

$("#TEXT").click(function(){

var content=editor.txt.text();

console.log(content);

alert(content);

})

//單擊獲取div標(biāo)簽中的json數(shù)據(jù)

$("#JSON").click(function(){

var content=editor.txt.getJSON();

var jsonStr =JSON.stringify(content);

console.log(jsonStr);

alert(jsonStr);

})

//單擊將文本內(nèi)容和圖片提交到數(shù)據(jù)庫

$("#submit").click(function(){

var content=editor.txt.html();

editor.txt.clear();

$.ajax({

url:'Servlet/Dele',//這里是個(gè)servlet

? ? ? ? ? type:"POST",

data: {"content":content,"id":$("#id").val(),"title":$("#title").val()},

dataType:"json",

success:function(da){

alert("成功上傳");

},

error:function () {

alert("上傳失敗,請(qǐng)重新嘗試或聯(lián)系管理人員!");

}

});

});

</script>

</body>

</html>

wangedit.java文件(處理圖片上傳到服務(wù)器的路徑):

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import java.util.UUID;

@WebServlet(name ="wangedit ",urlPatterns ="/wangedit/upload")

public class wangeditextends HttpServlet {

@Override

? ? protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");

resp.setContentType("text/json;charset=UTF-8");

JSONObject json =new JSONObject();

PrintWriter out = resp.getWriter();

//獲取上傳文件的id

? ? ? ? String id=req.getParameter("id");

//指定上傳位置

? ? ? ? String? path = req.getSession().getServletContext().getRealPath("upload/"+id+"/");

File saveDir =new File(path);

//如果目錄不存在,就創(chuàng)建目錄

? ? ? ? if(!saveDir.exists()){

saveDir.mkdir();

}

DiskFileItemFactory factory =new DiskFileItemFactory();

ServletFileUpload sfu =new ServletFileUpload(factory);

sfu.setHeaderEncoding("UTF-8");// 處理中文問題

? ? ? ? sfu.setSizeMax(10 *1024 *1024);// 限制文件大小

? ? ? ? String fileName ="";

try {

List? fileItems = sfu.parseRequest(req);

JSONArray arr =new JSONArray();//注意擺放的位置

? ? ? ? ? ? for (FileItem item : fileItems) {

//獲取文件的名字

? ? ? ? ? ? ? ? fileName = item.getName();

fileName = fileName.substring(fileName.lastIndexOf(".")+1);

fileName = UUID.randomUUID().toString() +"."+ fileName;

File saveFile =new File(path +"/" + fileName);//將文件保存到指定的路徑

? ? ? ? ? ? ? ? item.write(saveFile);

String imgUrl = req.getContextPath()+"/upload/"+id+"/"+fileName;

arr.add(imgUrl);

RouteStr.routeList.add(imgUrl);

}

json.put("errno",0);

json.put("data", arr);

out.print(json);

out.flush();

out.close();

}catch (Exception e) {

e.printStackTrace();

json.put("errno","200");

json.put("msg","服務(wù)器異常");

out.print(json.toString());

}

}

}

RouteStr.java文件(用來保存上傳圖片的路徑):

import java.util.ArrayList;

import java.util.List;

public class RouteStr {

public static? ListrouteList=new ArrayList();

}

DeleServlet.java文件(刪除服務(wù)器中多余的圖片,這里沒有做HTML代碼上傳數(shù)據(jù)庫的處理):

import com.test.www.pojo.News;

import com.test.www.service.NewsService;

import com.test.www.service.NewsServiceImpl;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

@WebServlet(name ="DeleServlet",urlPatterns ="/Servlet/Dele")

public class DeleServletextends HttpServlet {

@Override

? ? protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

this.doGet(request, response);

}

@Override

? ? protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

String routeStr = request.getParameter("content");

String id=request.getParameter("id");

String title=request.getParameter("title");

PrintWriter out=response.getWriter();

System.out.println(id);

System.out.println(title);

System.out.println(routeStr);

String[] routeArray=routeStr.split(" ");

List routeActList=new ArrayList();

for (int i=0;i

System.out.println(routeArray[i]);

if (routeArray[i].startsWith("src=\"/")) {

String? temp=routeArray[i].replace("\"","").replace("src=","");

routeActList.add(temp);

}

}

boolean isDele=true;

for (int j=0;j

for (int i=0;i

if(routeActList.get(i).equals(RouteStr.routeList.get(j))){

isDele=false;

}

}

if (isDele){

String fileName = RouteStr.routeList.get(j);

fileName=fileName.substring(fileName.lastIndexOf("/")+1);

String? ? path = request.getSession().getServletContext().getRealPath("upload/"+id+"/");

File file =new File(path +"/" + fileName);

if (file.exists()) {

file.delete();

System.out.println("刪除成功");

}

}else{

isDele=true;

}

}

NewsService newsService=new NewsServiceImpl();

News news=new News();

news.setId(Integer.parseInt(id));

news.setContent(routeStr);

news.setTitle(title);

boolean isSave=newsService.add(news);

System.out.println("保存"+isSave);

if (isSave){

RouteStr.routeList.clear();

System.out.println("保存成功!");

out.print(true);

}else{

System.out.println("保存失敗!");

for (int i=0;i

String fileName = RouteStr.routeList.get(i);

fileName=fileName.substring(fileName.lastIndexOf("/")+1);

String? ? path = request.getSession().getServletContext().getRealPath("upload/"+id+"/");

File file =new File(path +"/" + fileName);

if (file.exists()) {

file.delete();

}

}

RouteStr.routeList.clear();

}

out.flush();

out.close();

}

}

show.jsp文件(展示數(shù)據(jù)庫內(nèi)容):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>新聞內(nèi)容展示</title>

<script src="js/jquery.js" type="text/javascript" ></script>

<script type="text/javascript">

$(function () {

$.ajax({

url:"translate/Servlet",

type:"POST",

data:"opr=count",

dataType:"json",

success:showList,

error:function () {

alert("統(tǒng)計(jì)出錯(cuò),請(qǐng)重新嘗試或聯(lián)系管理人員!");

}

});

function showList(da) {

for (var i=0;i

$("#select").append("<option value=\""+(i+1)+"\">第"+(i+1)+"條</option>");

}

}

$("#submit").click(function(){

init();

});

function init() {

$.ajax({

url:'translate/Servlet',//這里是個(gè)servlet

? ? ? ? ? ? ? ? ? ? type:"POST",

data: {"id":$("#select").val(),"opr":"showList"},

dataType:"json",

success:function(da){

$("#title").html(da.title);

$("#context").html(da.content);

},

error:function () {

alert("上傳失敗,請(qǐng)重新嘗試或聯(lián)系管理人員!");

}

});

}

});

</script>

</head>

<body>

<select id="select"></select>

<input type="submit" id="submit" name="submit"? value="顯示"/>

<div id="title"></div>

<div id="context"></div>

</body>

</html>


效果展示:

編輯圖片的效果:

編輯內(nèi)容的顯示效果

從數(shù)據(jù)庫取出來的內(nèi)容顯示效果:

上面的方法是先利用集合存儲(chǔ)上傳服務(wù)器的圖片路徑,提交內(nèi)容以后再通過對(duì)比刪除多余的圖片。其中圖片的路徑是新聞編號(hào)作為目錄,缺點(diǎn)是還會(huì)有圖片的冗余。因?yàn)槎鄺l新聞可能會(huì)有相同的圖片。最終的解決辦法是定時(shí)從數(shù)據(jù)庫里取出路徑,和服務(wù)端的圖片路徑進(jìn)行比對(duì),定時(shí)清除。

3、總結(jié)

? ? ? 要實(shí)現(xiàn)上述功能,需要導(dǎo)入commons-fileupload.jar、commons-io.jar、fastjson.jar、json-lib-2.4-jdk15.jar這四種jar包。

? ? ?? 本篇內(nèi)容實(shí)現(xiàn)了利用wangEditor3上傳圖片到服務(wù)端、刪除服務(wù)端冗余的圖片、提交文本和圖片信息到數(shù)據(jù)庫、展示數(shù)據(jù)庫的內(nèi)容等等。

? ? ?? 如果這篇文章對(duì)你有幫助的話,也麻煩給個(gè)贊,激勵(lì)一下作者,謝謝大家!!!!!

? ? ?打個(gè)廣告,本人博客地址是:風(fēng)吟個(gè)人博客

??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,382評(píng)論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,616評(píng)論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,112評(píng)論 1 323
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,355評(píng)論 0 288
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,869評(píng)論 1 334
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,727評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,928評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,165評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評(píng)論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,585評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,892評(píng)論 2 372

推薦閱讀更多精彩內(nèi)容