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

1、內容處理

1.1 設置內容 ?

? ? ? ? 添加內容的方式有三種:第一種是直接將內容寫到要創建編輯器的<div>標簽中,第二種是在創建編輯器之后,使用editor.txt.html(...)設置編輯器內容,第三種是在創建編輯器之后,使用editor.txt.append('<p>追加的內容</p>')繼續追加內容。

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

1.2 獲取內容

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

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

1.3 使用textarea?

? ? ? ? wangEditor 從v3版本開始不支持 textarea ,但是可以通過onchange來實現 textarea 中提交富文本內容。

2、上傳圖片

? ??默認情況下,編輯器不會顯示“上傳圖片”的tab,因為你還沒有配置上傳圖片的信息。有兩種方式可以實現顯示“上傳圖片”的tab,一是在編輯器創建之前添加editor.customConfig. uploadImgShowBase64 = true,使用 base64 保存圖片;二是在編輯器創建之前添加editor.custom Config.uploadImgServer = '/upload',上傳圖片到服務器。

? ? 默認情況下,“網絡圖片”tab是一直存在的。如果不需要,可以在編輯器創建之前添加editor.customConfig.showLinkImg = false,隱藏“網絡圖片”tab。

2.1? 上傳圖片到服務器

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

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

代碼示例如下:

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"/>

新聞標題:<input type="text" id="title" name="title"/><br>

新聞內容:

<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 () {

//獲得數據庫中新聞數目并賦值給隱藏域

$.ajax({

url:"translate/Servlet",

type:"POST",

data:"opr=count",

dataType:"json",

success:function (da) {

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

},

error:function () {

alert("統計出錯,請重新嘗試或聯系管理人員!");

}

});

});

</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*/

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

? 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(),//這里是個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) {

// 監控變化,同步更新到 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);

})

//單擊獲取文本內容

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

var content=editor.txt.text();

console.log(content);

alert(content);

})

//單擊獲取div標簽中的json數據

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

var content=editor.txt.getJSON();

var jsonStr =JSON.stringify(content);

console.log(jsonStr);

alert(jsonStr);

})

//單擊將文本內容和圖片提交到數據庫

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

var content=editor.txt.html();

editor.txt.clear();

$.ajax({

url:'Servlet/Dele',//這里是個servlet

? ? ? ? ? type:"POST",

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

dataType:"json",

success:function(da){

alert("成功上傳");

},

error:function () {

alert("上傳失敗,請重新嘗試或聯系管理人員!");

}

});

});

</script>

</body>

</html>

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

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);

//如果目錄不存在,就創建目錄

? ? ? ? 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","服務器異常");

out.print(json.toString());

}

}

}

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

import java.util.ArrayList;

import java.util.List;

public class RouteStr {

public static? ListrouteList=new ArrayList();

}

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

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文件(展示數據庫內容):

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

<html>

<head>

<title>新聞內容展示</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("統計出錯,請重新嘗試或聯系管理人員!");

}

});

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',//這里是個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("上傳失敗,請重新嘗試或聯系管理人員!");

}

});

}

});

</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>


效果展示:

編輯圖片的效果:

編輯內容的顯示效果

從數據庫取出來的內容顯示效果:

上面的方法是先利用集合存儲上傳服務器的圖片路徑,提交內容以后再通過對比刪除多余的圖片。其中圖片的路徑是新聞編號作為目錄,缺點是還會有圖片的冗余。因為多條新聞可能會有相同的圖片。最終的解決辦法是定時從數據庫里取出路徑,和服務端的圖片路徑進行比對,定時清除。

3、總結

? ? ? 要實現上述功能,需要導入commons-fileupload.jar、commons-io.jar、fastjson.jar、json-lib-2.4-jdk15.jar這四種jar包。

? ? ?? 本篇內容實現了利用wangEditor3上傳圖片到服務端、刪除服務端冗余的圖片、提交文本和圖片信息到數據庫、展示數據庫的內容等等。

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

? ? ?打個廣告,本人博客地址是:風吟個人博客

??

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容