目录结构
- index.jsp
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
pageContext.setAttribute("path",path);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<title>CKEditor</title>
<style type="text/css">
* {
font-family: "宋体";
font-size: 14px
}
</style>
</head>
<body>
<script type="text/javascript">
function addNum(){
var data = CKEDITOR.instances.content.getData();
window.location.href="${path}/picDao?pic="+data;
}
</script>
<form id="form1" name="form1" method="post" action="">
<table width="650" height="400" border="0" align="center">
<tr>
<td>主题:</td>
<td><input name="title" type="text" id="title" size="80"
maxlength="80" /> </td>
</tr>
<tr>
<td valign="top">内容:</td>
<td><textarea cols="80" id="content" name="content">
</textarea>
<script type="text/javascript">
CKEDITOR.replace('content',{filebrowserUploadUrl : '${path}/ckeditor/uploader?Type=File',
filebrowserImageUploadUrl : '${path}/ckeditor/uploader?Type=Image',
filebrowserFlashUploadUrl : '${path}/ckeditor/uploader?Type=Flash'
});
</script></td>
</tr>
<tr>
<td></td>
<td><input type="submit" onclick=addNum() name="Submit" value="提交" /> <input
type="reset" name="Reset" value="重置" /></td>
</tr>
</table>
</form>
</body>
</html>
- display.jsp (修改action路径测试)
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display Content</title>
</head>
<%request.setCharacterEncoding("UTF-8"); %>
<center>
<table width="600" border="0" bordercolor="000000"
style="table-layout: fixed;">
<tr>
<td width="100" bordercolor="ffffff">主题:</td>
<td width="500" bordercolor="ffffff">${param.title}</td>
</tr>
<tr>
<td valign="top" bordercolor="ffffff">内容:</td>
<td valign="top" bordercolor="ffffff">${param.content}</td>
</tr>
</table>
</center>
</html>
- config.js(取出图片区乱码) 还需要打开image.js的图片上床功能
config.image_previewText=' '; //预览区域显示内容
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>CKEditorPicUp</display-name>
<servlet>
<servlet-name>SimpleUploader</servlet-name>
<servlet-class>ckeditor.CKEditorUploadServlet</servlet-class>
<init-param>
<param-name>baseDir</param-name>
<param-value>/UserFiles/</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>enabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>AllowedExtensionsFile</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>DeniedExtensionsFile</param-name>
<param-value>
html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|ftl
</param-value>
</init-param>
<init-param>
<param-name>AllowedExtensionsImage</param-name>
<param-value>jpg|gif|jpeg|png|bmp</param-value>
</init-param>
<init-param>
<param-name>DeniedExtensionsImage</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>AllowedExtensionsFlash</param-name>
<param-value>swf|fla</param-value>
</init-param>
<init-param>
<param-name>DeniedExtensionsFlash</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SimpleUploader</servlet-name>
<url-pattern>/ckeditor/uploader</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ATextDao</display-name>
<servlet-name>ATextDao</servlet-name>
<servlet-class>Dao.ATextDao</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ATextDao</servlet-name>
<url-pattern>/ATextDao</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>picDao</display-name>
<servlet-name>picDao</servlet-name>
<servlet-class>Dao.picDao</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>picDao</servlet-name>
<url-pattern>/picDao</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>picDao1</display-name>
<servlet-name>picDao1</servlet-name>
<servlet-class>Dao.picDao1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>picDao1</servlet-name>
<url-pattern>/picDao1</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>picDao2</display-name>
<servlet-name>picDao2</servlet-name>
<servlet-class>Dao.picDao2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>picDao2</servlet-name>
<url-pattern>/picDao2</url-pattern>
</servlet-mapping>
</web-app>
- CKEditorUploadServlet (网上搜的亲测可用)
package ckeditor;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CKEditorUploadServlet extends HttpServlet {
private static String baseDir;// CKEditor的根目录
private static boolean debug = false;// 是否debug模式
private static boolean enabled = false;// 是否开启CKEditor上传
private static Hashtable allowedExtensions;// 允许的上传文件扩展名
private static Hashtable deniedExtensions;// 阻止的上传文件扩展名
private static SimpleDateFormat dirFormatter;// 目录命名格式:yyyyMM
private static SimpleDateFormat fileFormatter;// 文件命名格式:yyyyMMddHHmmssSSS
/**
* Servlet初始化方法
*/
public void init() throws ServletException {
// 从web.xml中读取debug模式
debug = (new Boolean(getInitParameter("debug"))).booleanValue();
if (debug)
System.out.println("\r\n---- SimpleUploaderServlet initialization started ----");
// 格式化目录和文件命名方式
dirFormatter = new SimpleDateFormat("yyyyMM");
fileFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
// 从web.xml中获取根目录名称
baseDir = getInitParameter("baseDir");
// 从web.xml中获取是否可以进行文件上传
enabled = (new Boolean(getInitParameter("enabled"))).booleanValue();
if (baseDir == null)
baseDir = "/UserFiles/";
String realBaseDir = getServletContext().getRealPath(baseDir);
File baseFile = new File(realBaseDir);
if (!baseFile.exists()) {
baseFile.mkdirs();
}
// 实例化允许的扩展名和阻止的扩展名
allowedExtensions = new Hashtable(3);
deniedExtensions = new Hashtable(3);
// 从web.xml中读取配置信息
allowedExtensions.put("File",
stringToArrayList(getInitParameter("AllowedExtensionsFile")));
deniedExtensions.put("File",
stringToArrayList(getInitParameter("DeniedExtensionsFile")));
allowedExtensions.put("Image",
stringToArrayList(getInitParameter("AllowedExtensionsImage")));
deniedExtensions.put("Image", stringToArrayList(getInitParameter("DeniedExtensionsImage")));
allowedExtensions.put("Flash", stringToArrayList(getInitParameter("AllowedExtensionsFlash")));
deniedExtensions.put("Flash", stringToArrayList(getInitParameter("DeniedExtensionsFlash")));
if (debug)
System.out.println("---- SimpleUploaderServlet initialization completed ----\r\n");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (debug)
System.out.println("--- BEGIN DOPOST ---");
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
// 从请求参数中获取上传文件的类型:File/Image/Flash
String typeStr = request.getParameter("Type");
if (typeStr == null) {
typeStr = "File";
}
if (debug)
System.out.println(typeStr);
// 实例化dNow对象,获取当前时间
Date dNow = new Date();
// 设定上传文件路径
String currentPath = baseDir + typeStr + "/"
+ dirFormatter.format(dNow);
// 获得web应用的上传路径
String currentDirPath = getServletContext().getRealPath(currentPath);
// 判断文件夹是否存在,不存在则创建
File dirTest = new File(currentDirPath);
if (!dirTest.exists()) {
dirTest.mkdirs();
}
// 将路径前加上web应用名
currentPath = request.getContextPath() + currentPath;
if (debug)
System.out.println(currentDirPath);
// 文件名和文件真实路径
String newName = "";
String fileUrl = "";
if (enabled) {
// 使用Apache Common组件中的fileupload进行文件上传
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Map fields = new HashMap();
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField())
fields.put(item.getFieldName(), item.getString());
else
fields.put(item.getFieldName(), item);
}
// CEKditor中file域的name值是upload
FileItem uplFile = (FileItem) fields.get("upload");
// 获取文件名并做处理
String fileNameLong = uplFile.getName();
fileNameLong = fileNameLong.replace('\\', '/');
String[] pathParts = fileNameLong.split("/");
String fileName = pathParts[pathParts.length - 1];
// 获取文件扩展名
String ext = getExtension(fileName);
// 设置上传文件名
fileName = fileFormatter.format(dNow) + "." + ext;
// 获取文件名(无扩展名)
String nameWithoutExt = getNameWithoutExtension(fileName);
File pathToSave = new File(currentDirPath, fileName);
fileUrl = currentPath + "/" + fileName;
if (extIsAllowed(typeStr, ext)) {
int counter = 1;
while (pathToSave.exists()) {
newName = nameWithoutExt + "_" + counter + "." + ext;
fileUrl = currentPath + "/" + newName;
pathToSave = new File(currentDirPath, newName);
counter++;
}
uplFile.write(pathToSave);
} else {
if (debug)
System.out.println("无效的文件类型: " + ext);
}
} catch (Exception ex) {
if (debug)
ex.printStackTrace();
}
} else {
if (debug)
System.out.println("未开启CKEditor上传功能");
}
// CKEditorFuncNum是回调时显示的位置,这个参数必须有
String callback = request.getParameter("CKEditorFuncNum");
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
+ ",'" + fileUrl + "',''" + ")");
out.println("</script>");
out.flush();
out.close();
System.out.println(callback);
//将图片路径存入到数据库中
//response.sendRedirect(request.getContextPath()+"/ATextDao?a="+fileUrl);
if (debug)
System.out.println("--- END DOPOST ---");
}
/**
* 获取文件名的方法
*/
private static String getNameWithoutExtension(String fileName) {
return fileName.substring(0, fileName.lastIndexOf("."));
}
/**
* 获取扩展名的方法
*/
private String getExtension(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
/**
* 字符串像ArrayList转化的方法
*/
private ArrayList stringToArrayList(String str) {
if (debug)
System.out.println(str);
String[] strArr = str.split("\\|");
ArrayList tmp = new ArrayList();
if (str.length() > 0) {
for (int i = 0; i < strArr.length; ++i) {
if (debug)
System.out.println(i + " - " + strArr[i]);
tmp.add(strArr[i].toLowerCase());
}
}
return tmp;
}
/**
* 判断扩展名是否允许的方法
*/
private boolean extIsAllowed(String fileType, String ext) {
ext = ext.toLowerCase();
ArrayList allowList = (ArrayList) allowedExtensions.get(fileType);
ArrayList denyList = (ArrayList) deniedExtensions.get(fileType);
if (allowList.size() == 0) {
if (denyList.contains(ext)) {
return false;
} else {
return true;
}
}
if (denyList.size() == 0) {
if (allowList.contains(ext)) {
return true;
} else {
return false;
}
}
return false;
}
}
- ATextDao(将图片路径存放到数据库中)
package Dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ATextDao extends HttpServlet {
private static final long serialVersionUID = 1L;
public ATextDao() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//String a=request.getParameter("a");
String a=(String) request.getAttribute("a");
System.out.println(a);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
String sql = "insert into text(text) value('"+a+"')";
PreparedStatement ps = conn.prepareStatement(sql);
ps.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
- picDao(将图片路径存放到数据库中)
package Dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class picDao extends HttpServlet {
private static final long serialVersionUID = 1L;
public picDao() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String picurl=request.getParameter("pic");
System.out.println(picurl);
String rgex = "src=\"(.*?)\"";
System.out.println("截出的字符串:"+regex.DealStrSub.getSubUtilSimple(picurl, rgex));
String a = regex.DealStrSub.getSubUtilSimple(picurl, rgex);
request.setAttribute("a",a);
//向数据库中存放bate64格式的地址
request.getRequestDispatcher("/picDao1").forward(request, response);
//向数据库存放图片路径
//request.getRequestDispatcher("/ATextDao").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
- picDao1(将64格式存到数据库中,数据库中列类型是longtext)
package Dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import product.domeImage;
/**
* Servlet implementation class picDao1
*/
public class picDao1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public picDao1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//String a=request.getParameter("a");
//处理地址
String a=(String) request.getAttribute("a");
a=a.replace('/','\\');
String b="E:\\workspace1\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps";
a=b+a;
System.out.println(a);
//转化成bit64格式
String base64 = domeImage.imageToBase64(a);
System.out.println(base64+"+++++++++++");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
String sql = "insert into pic(pic) value('"+base64+"')";
PreparedStatement ps = conn.prepareStatement(sql);
ps.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
- picDao2(从数据库中解码出base64的数据存放)
package Dao;
import java.io.*;
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import product.domeImage;
public class picDao2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public picDao2() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
ps=conn.prepareStatement("select * from pic where id=?");
ps.setInt(1,1);
rs=ps.executeQuery();
while(rs.next()) {
String base64 =(String) rs.getObject(2);//这。。。。
System.out.print(base64);
domeImage.base64ToImage(base64, "D:\\k.jpg");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
- domeImage(网上找的,处理base64的方法)
package product;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class domeImage {
/**
* @Descriptionmap 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
* @author
* @Date
* @param path 图片路径
* @return
*/
public static String imageToBase64(String path) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* @Descriptionmap 对字节数组字符串进行Base64解码并生成图片
* @author
* @Date 2016-12-06
* @param base64 图片Base64数据
* @param path 图片路径
* @return
*/
public static boolean base64ToImage(String base64, String path) {// 对字节数组字符串进行Base64解码并生成图片
if (base64 == null){ // 图像数据为空
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(path);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
//测试
/*public static void main(String[] str) throws Exception {
String path = "E:\\workspace1\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\CKEditorPicUp\\UserFiles\\Image\\201809";
String base64 = domeImage.imageToBase64(path);
domeImage.base64ToImage(base64, "D:\\k.jpg");
System.out.println(base64+"+++++++++++");
}*/
}
- DealStrSub(对getData方法得到的html代码进行处理获取路径)
package regex;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DealStrSub {
/**
* 正则表达式匹配两个指定字符串中间的内容
* @param soap
* @return
*/
public static List<String> getSubUtil(String soap,String rgex){
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile(rgex);// 匹配的模式
Matcher m = pattern.matcher(soap);
while (m.find()) {
int i = 1;
list.add(m.group(i));
i++;
}
return list;
}
/**
* 返回单个字符串,若匹配到多个的话就返回第一个,方法与getSubUtil一样
* @param soap
* @param rgex
* @return
*/
public static String getSubUtilSimple(String soap,String rgex){
Pattern pattern = Pattern.compile(rgex);// 匹配的模式
Matcher m = pattern.matcher(soap);
while(m.find()){
return m.group(1);
}
return "";
}
/**
* 测试
* @param args
*/
/* public static void main(String[] args) {
String str ="<p><img alt='' src='/C/UserFiles/Image/201809/20180913080249445.jpg' style='height:300px; width:658px' /></p>";
String rgex = "src='(.*?)'";
System.out.println(getSubUtil(str,rgex));
System.out.println(getSubUtilSimple(str, rgex));
} */
}