ckeditor servlet 그림 업로드 설정 실현
작은 버그 가 있 습 니 다. [중국어 사진 업로드 가 지원 되 지 않 습 니 다.]
웹. xml 관련 설정
그 중 baseDir 는 파일 이 업 로드 된 디 렉 터 리 입 니 다.
<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>false</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 의 전체 원본 코드
package ckeditor;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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
*/
@SuppressWarnings("unchecked")
public void init() throws ServletException {
// web.xml debug
debug = (new Boolean(getInitParameter("debug"))).booleanValue();
if (debug)
System.out
.println("\r
---- 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
");
}
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();
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;
}
}
테스트 페이지
<%@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/ckeditor.js"></script>
<title>CKEditor</title>
<style type="text/css">
* {
font-family: " ";
font-size: 14px
}
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="/ckeditor/display.jsp">
<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" name="Submit" value=" " /> <input
type="reset" name="Reset" value=" " /></td>
</tr>
</table>
</form>
</body>
</html>
display.jsp
<%@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>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
5분 안에 JSP 배우기Java 생태계는 지난 20년 동안 많이 발전했으며 이는 시장에서 변함없이 인기를 얻고 있음으로 알 수 있습니다. 글쎄, 이것은 다른 프로그래밍 언어 중 하나에 대한 탄탄한 배경이 있거나 새로운 개발자이지만 시간이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.