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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 7,295評(píng)論 0 17
  • 本文包括:1、文件上傳概述2、利用 Commons-fileupload 組件實(shí)現(xiàn)文件上傳3、核心API——Dis...
    廖少少閱讀 12,742評(píng)論 5 91
  • 人類的進(jìn)化起源知道了。 有一個(gè)好奇的問題, 我想去研究。 病毒是怎么回事? 它從哪里來? 為什么它的遺傳復(fù)制功能如...
    蘭郡子閱讀 368評(píng)論 8 3

友情鏈接更多精彩內(nèi)容