美文网首页互联网科技JavaJavaWeb技术
wangEditor3上传图片到服务器以及删除服务器多余的图片(

wangEditor3上传图片到服务器以及删除服务器多余的图片(

作者: 问题_解决_分享_讨论_最优 | 来源:发表于2019-07-01 20:23 被阅读0次

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上传图片到服务端、删除服务端冗余的图片、提交文本和图片信息到数据库、展示数据库的内容等等。

       如果这篇文章对你有帮助的话,也麻烦给个赞,激励一下作者,谢谢大家!!!!!

     打个广告,本人博客地址是:风吟个人博客

  

相关文章

网友评论

    本文标题:wangEditor3上传图片到服务器以及删除服务器多余的图片(

    本文链接:https://www.haomeiwen.com/subject/oekvcctx.html