浏览 2230 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (8) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-05-12
fckeditor上传目录,根据登陆用户不同,显示的文件夹路径也不同。
版本是2.3 for java,几年了,虽然有点老,但很好用。
附上代码
<!-- FCKEditor --> <servlet> <servlet-name>Connector</servlet-name> <servlet-class>org.dy.ext.web.fckeditor.IncrexConnectorServlet</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> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>SimpleUploader</servlet-name> <servlet-class>org.dy.ext.web.fckeditor.IncrexUploaderServlet</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>maxSize</param-name> <param-value>1024</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>php|php3|php5|phtml|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|dll|reg|cgi</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>php|php3|php5|phtml|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|dll|reg|cgi</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>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Connector</servlet-name> <url-pattern>/crud/editor/fckeditor/editor/filemanager/browser/default/connectors/jsp/connector</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SimpleUploader</servlet-name> <url-pattern>/crud/editor/fckeditor/editor/filemanager/upload/simpleuploader</url-pattern> </servlet-mapping> <!-- FCKEditor -->
Java代码
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == */ package org.dy.ext.web.fckeditor; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; 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 javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.dy.util.IOHelper; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.cisee.increx.base.auth.UserBean; import com.cisee.increx.base.auth.web.AuthAction; /** * Servlet to upload and browse files.<br> * * This servlet accepts 4 commands used to retrieve and create files and folders * from a server directory. The allowed commands are: * <ul> * <li>GetFolders: Retrive the list of directory under the current folder * <li>GetFoldersAndFiles: Retrive the list of files and directory under the * current folder * <li>CreateFolder: Create a new directory under the current folder * <li>FileUpload: Send a new file to the server (must be sent with a POST) * </ul> * * @author Simone Chiaretta (simo@users.sourceforge.net) */ public class IncrexConnectorServlet extends HttpServlet { private static String baseDir; private static String srcBaseDir; private static boolean debug = false; /** * Initialize the servlet.<br> * Retrieve from the servlet configuration the "baseDir" which is the root * of the file repository:<br> * If not specified the value of "/UserFiles/" will be used. * */ public void init() throws ServletException { baseDir = getInitParameter("baseDir"); debug = (new Boolean(getInitParameter("debug"))).booleanValue(); if (baseDir == null) baseDir = "/userfiles/"; srcBaseDir = baseDir; String realBaseDir = getServletContext().getRealPath(baseDir); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { try { IOHelper.createDirectoryTreeForFolder(realBaseDir); } catch (IOException e) { // e.printStackTrace(); } } } /** * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It execute the command and then return the results to the client in XML * format. * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Authorization need login first UserBean user = AuthAction.getUserStatusBean(request); if(user == null){ System.out.println("Not login yet for : " + request.getRemoteHost()); throw new ServletException("Need login first!"); }else{ // change upload directory by enterprisecode and userid // eg. /userfiles/xiao/2/ this.baseDir = srcBaseDir + user.getEnterprisecode() + "/" + user.getUid() + "/"; String realBaseDir = getServletContext().getRealPath(baseDir); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { try { IOHelper.createDirectoryTreeForFolder(realBaseDir); } catch (IOException e) { // e.printStackTrace(); } } } if (debug) System.out.println("--- BEGIN DOGET ---"); response.setContentType("text/xml; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); File currentDir = new File(currentDirPath); if (!currentDir.exists()) { try { IOHelper.createDirectoryTreeForFolder(currentDirPath); } catch (IOException e) { // e.printStackTrace(); } } Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr, request.getContextPath() + currentPath); if (debug) System.out.println("Command = " + commandStr); if (commandStr.equals("GetFolders")) { getFolders(currentDir, root, document); } else if (commandStr.equals("GetFoldersAndFiles")) { getFolders(currentDir, root, document); getFiles(currentDir, root, document); } else if (commandStr.equals("CreateFolder")) { String newFolderStr = request.getParameter("NewFolderName"); File newFolder = new File(currentDir, newFolderStr); String retValue = "110"; if (newFolder.exists()) { retValue = "101"; } else { try { boolean dirCreated = newFolder.mkdir(); if (dirCreated) retValue = "0"; else retValue = "102"; } catch (SecurityException sex) { retValue = "103"; } } setCreateFolderResponse(retValue, root, document); } document.getDocumentElement().normalize(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(out); transformer.transform(source, result); if (debug) { StreamResult dbgResult = new StreamResult(System.out); transformer.transform(source, dbgResult); System.out.println(""); System.out.println("--- END DOGET ---"); } } catch (Exception ex) { ex.printStackTrace(); } out.flush(); out.close(); baseDir = srcBaseDir; } /** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Authorization need login first UserBean user = AuthAction.getUserStatusBean(request); if(user == null){ System.out.println("Not login yet for : " + request.getRemoteHost()); throw new ServletException("Need login first!"); }else{ // change upload directory by enterprisecode and userid // eg. /userfiles/xiao/2/ this.baseDir = srcBaseDir + user.getEnterprisecode() + "/" + user.getUid() + "/"; String realBaseDir = getServletContext().getRealPath(baseDir); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { try { IOHelper.createDirectoryTreeForFolder(realBaseDir); } catch (IOException e) { // e.printStackTrace(); } } } if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); 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); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); baseDir = srcBaseDir; if (debug) System.out.println("--- END DOPOST ---"); } private void setCreateFolderResponse(String retValue, Node root, Document doc) { Element myEl = doc.createElement("Error"); myEl.setAttribute("number", retValue); root.appendChild(myEl); } private void getFolders(File dir, Node root, Document doc) { Element folders = doc.createElement("Folders"); root.appendChild(folders); File[] fileList = dir.listFiles(); for (int i = 0; i < fileList.length; ++i) { if (fileList[i].isDirectory()) { Element myEl = doc.createElement("Folder"); myEl.setAttribute("name", fileList[i].getName()); folders.appendChild(myEl); } } } private void getFiles(File dir, Node root, Document doc) { Element files = doc.createElement("Files"); root.appendChild(files); File[] fileList = dir.listFiles(); for (int i = 0; i < fileList.length; ++i) { if (fileList[i].isFile()) { Element myEl = doc.createElement("File"); myEl.setAttribute("name", fileList[i].getName()); myEl.setAttribute("size", "" + fileList[i].length() / 1024); files.appendChild(myEl); } } } private Node CreateCommonXml(Document doc, String commandStr, String typeStr, String currentPath, String currentUrl) { Element root = doc.createElement("Connector"); doc.appendChild(root); root.setAttribute("command", commandStr); root.setAttribute("resourceType", typeStr); Element myEl = doc.createElement("CurrentFolder"); myEl.setAttribute("path", currentPath); myEl.setAttribute("url", currentUrl); root.appendChild(myEl); return root; } /* * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF * bug #991489 */ private static String getNameWithoutExtension(String fileName) { return fileName.substring(0, fileName.lastIndexOf(".")); } /* * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF * bug #991489 */ private String getExtension(String fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1); } }
/* * FCKeditor - The text editor for internet * Copyright (C) 2003-2005 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * File Name: SimpleUploaderServlet.java * Java File Uploader class. * * Version: 2.3 * Modified: 2005-08-11 16:29:00 * * File Authors: * Simone Chiaretta (simo@users.sourceforge.net) */ package org.dy.ext.web.fckeditor; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; 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.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.dy.util.IOHelper; import com.cisee.increx.base.auth.UserBean; import com.cisee.increx.base.auth.web.AuthAction; /** * Servlet to upload files.<br> * * This servlet accepts just file uploads, eventually with a parameter * specifying file type * * @author Simone Chiaretta (simo@users.sourceforge.net) */ public class IncrexUploaderServlet extends HttpServlet { private static final int DEFAULT_MAX_SIZE = 1024*1024; private static String baseDir; private static String srcBaseDir; private static boolean debug = false; private static boolean enabled = false; private static Hashtable allowedExtensions; private static Hashtable deniedExtensions; private static String encoding; private static int maxSize; /** * Initialize the servlet.<br> * Retrieve from the servlet configuration the "baseDir" which is the root * of the file repository:<br> * If not specified the value of "/UserFiles/" will be used.<br> * Also it retrieve all allowed and denied extensions to be handled. * */ public void init() throws ServletException { debug = (new Boolean(getInitParameter("debug"))).booleanValue(); if (debug) System.out.println("\r\n---- SimpleUploaderServlet initialization started ----"); baseDir = getInitParameter("baseDir"); enabled = (new Boolean(getInitParameter("enabled"))).booleanValue(); if (baseDir == null) baseDir = "/userfiles/"; srcBaseDir = baseDir; encoding = getInitParameter("encoding"); if (encoding == null) encoding = "utf-8"; String maxSizeString = getInitParameter("maxSize"); if(maxSizeString != null) maxSize = 1024*Integer.parseInt(maxSizeString); else maxSize = DEFAULT_MAX_SIZE; String realBaseDir = getServletContext().getRealPath(baseDir); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { try { IOHelper.createDirectoryTreeForFolder(realBaseDir); } catch (IOException e) { // e.printStackTrace(); } } allowedExtensions = new Hashtable(3); deniedExtensions = new Hashtable(3); 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"); } /** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Authorization need login first UserBean user = AuthAction.getUserStatusBean(request); if(user == null){ System.out.println("Not login yet for : " + request.getRemoteHost()); throw new ServletException("Need login first!"); }else{ // change upload directory by enterprisecode and userid // eg. /userfiles/xiao/2/ this.baseDir = srcBaseDir + user.getEnterprisecode() + "/" + user.getUid() + "/"; } if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=" + encoding); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); if (typeStr == null) typeStr = "File"; String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); upload.setFileSizeMax(maxSize); 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); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(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; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); baseDir = srcBaseDir; } /* * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF * bug #991489 */ private static String getNameWithoutExtension(String fileName) { return fileName.substring(0, fileName.lastIndexOf(".")); } /* * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF * bug #991489 */ private String getExtension(String fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1); } /** * Helper function to convert the configuration string to an 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 String stringFromParam(String str) { return str.replace("|", ","); } /** * Helper function to verify if a file extension is allowed or not allowed. */ 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; } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |