很早以前就想把CKEditor在JSP下的圖片上傳及瀏覽伺服器圖片的方法寫下來了,不過因為教學項目中要用到,擔心HEM直接套用,自己不去調查(我可是用心良苦啊),不能很好的鍛煉,一直沒寫出來,今天項目開始測試了,他們的功能也都基本可以結束了,我也可以發我的帖了。
寫這個的起因是在網上一仁兄的文章,抱怨說CKEditor不支援JSP了,感歎了許多,說支援ASP、PHP,就是不支援JSP,於是俺也在網上找了找JSP方面的資料,看來確實不支援了,不過人家也是有道理的,畢竟JSP上傳的圖片,不能簡單的用個JSP就隨便搞搞就O了。
關於CKEditor在JSP下上傳圖片的方法,網上有很多,大都是寫了一大堆JS代碼然後自己註冊一個事件,寫的太多,我沒怎麼看懂,不過有一位大俠寫的讓我看到了簡單寫法的曙光(不過遺憾的是,時間太長了,不知道大俠的URL了)。
言歸正傳,對於上傳CKEditor已經做好了,我們只要準備個功能,接收CKEditor提交過來的檔案就可以了,所以呢實現的思路是:
- 準備一下JSP上傳檔案的JAR包:commons-fileupload.jar和commons-io.jar
- 編寫一個JSP用於接收上傳的檔案(這裡除上傳圖片功能外,需調用一個核心JS語句)
- 編寫一個JSP用於瀏覽檔案(這裡除上傳圖片功能外,需調用一個核心JS語句)
- 修改CKEditor的config.js,將上傳檔案和瀏覽檔案的JSP配置進去
說明一下,之所以採用JSP沒有使用Servlet,那是因為JSP簡單啊,這樣可以降低CKEditor對項目的侵入性啊。下面看代碼啦:
用於接收上傳的檔案的JSP:Java代碼
- <%@page import="java.io.File"%>
- <%@page import="java.util.UUID"%>
- <%@page import="org.apache.commons.fileupload.FileItem"%>
- <%@page import="java.util.List"%>
- <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
- <%@page import="org.apache.commons.fileupload.FileItemFactory"%>
- <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
- <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <title>JSP上傳檔案</title>
- </head>
- <body>
- <%
- String path = request.getContextPath() + "/";
- if(ServletFileUpload.isMultipartContent(request)){
- String type = "";
- if(request.getParameter("type") != null)//擷取檔案分類
- type = request.getParameter("type").toLowerCase() + "/";
- String callback = request.getParameter("CKEditorFuncNum");//擷取回調JS的函數Num
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
- servletFileUpload.setHeaderEncoding("UTF-8");//解決檔案名稱亂碼的問題
- List<FileItem> fileItemsList = servletFileUpload.parseRequest(request);
- for (FileItem item : fileItemsList) {
- if (!item.isFormField()) {
- String fileName = item.getName();
- fileName = "file" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
- //定義檔案路徑,根據你的檔案夾結構,可能需要做修改
- String clientPath = "ckeditor/uploader/upload/" + type + fileName;
-
- //儲存檔案到伺服器上
- File file = new File(request.getSession().getServletContext().getRealPath(clientPath));
- if (!file.getParentFile().exists()) {
- file.getParentFile().mkdirs();
- }
- item.write(file);
-
- //列印一段JS,調用parent頁面的CKEditor的函數,傳遞函數編號和上傳後檔案的路徑;這句很重要,成敗在此一句
- out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("+callback+",'"+path+clientPath+"')</script>");
- break;
- }
- }
- }
- %>
- </body>
- </html>
<%@page import="java.io.File"%><%@page import="java.util.UUID"%><%@page import="org.apache.commons.fileupload.FileItem"%><%@page import="java.util.List"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@page import="org.apache.commons.fileupload.FileItemFactory"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><title>JSP上傳檔案</title></head><body><%String path = request.getContextPath() + "/";if(ServletFileUpload.isMultipartContent(request)){String type = "";if(request.getParameter("type") != null)//擷取檔案分類type = request.getParameter("type").toLowerCase() + "/";String callback = request.getParameter("CKEditorFuncNum");//擷取回調JS的函數NumFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload servletFileUpload = new ServletFileUpload(factory);servletFileUpload.setHeaderEncoding("UTF-8");//解決檔案名稱亂碼的問題List<FileItem> fileItemsList = servletFileUpload.parseRequest(request);for (FileItem item : fileItemsList) {if (!item.isFormField()) {String fileName = item.getName();fileName = "file" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));//定義檔案路徑,根據你的檔案夾結構,可能需要做修改String clientPath = "ckeditor/uploader/upload/" + type + fileName;//儲存檔案到伺服器上File file = new File(request.getSession().getServletContext().getRealPath(clientPath));if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}item.write(file);//列印一段JS,調用parent頁面的CKEditor的函數,傳遞函數編號和上傳後檔案的路徑;這句很重要,成敗在此一句out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("+callback+",'"+path+clientPath+"')</script>");break;}}} %></body></html>
用於瀏覽檔案的JSP:Java代碼
- <%@page import="java.io.File"%>
- <%@ page language="java" contentType="text/html; charset=GB18030"
- pageEncoding="GB18030"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <title>圖片瀏覽</title>
- <script type="text/javascript">
- //這段函數是重點,不然不能和CKEditor互動了
- function funCallback(funcNum,fileUrl){
- var parentWindow = ( window.parent == window ) ? window.opener : window.parent;
- parentWindow.CKEDITOR.tools.callFunction(funcNum, fileUrl);
- window.close();
- }
- </script>
- </head>
- <body>
- <%
- String path = request.getContextPath() + "/";
- String type = "";
- if(request.getParameter("type") != null)//擷取檔案分類
- type = request.getParameter("type").toLowerCase() + "/";
- String clientPath = "ckeditor/uploader/upload/" + type;
- File root = new File(request.getSession().getServletContext().getRealPath(clientPath));
- if(!root.exists()){
- root.mkdirs();
- }
- String callback = request.getParameter("CKEditorFuncNum");
- File[] files = root.listFiles();
- if(files.length > 0){
- for(File file:files ) {
- String src = path + clientPath + file.getName();
- out.println("<img width='110px' height='70px' src='" + src + "' alt='" + file.getName() + "' onclick=\"funCallback("+callback+",'"+ src +"')\">");
- }
- }else{
- out.println("<h3>未檢測到資源。</h3>");
- }
- %>
- </body>
- </html>
<%@page import="java.io.File"%><%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><title>圖片瀏覽</title><script type="text/javascript">//這段函數是重點,不然不能和CKEditor互動了function funCallback(funcNum,fileUrl){var parentWindow = ( window.parent == window ) ? window.opener : window.parent;parentWindow.CKEDITOR.tools.callFunction(funcNum, fileUrl);window.close();}</script></head><body><%String path = request.getContextPath() + "/";String type = "";if(request.getParameter("type") != null)//擷取檔案分類type = request.getParameter("type").toLowerCase() + "/";String clientPath = "ckeditor/uploader/upload/" + type;File root = new File(request.getSession().getServletContext().getRealPath(clientPath));if(!root.exists()){root.mkdirs();}String callback = request.getParameter("CKEditorFuncNum");File[] files = root.listFiles();if(files.length > 0){for(File file:files ) {String src = path + clientPath + file.getName();out.println("<img width='110px' height='70px' src='" + src + "' alt='" + file.getName() + "' onclick=\"funCallback("+callback+",'"+ src +"')\">");}}else{out.println("<h3>未檢測到資源。</h3>");} %></body></html>
修改後的CKEditor的config.js: Js代碼
- CKEDITOR.editorConfig = function( config )
- {
- config.language = 'zh-cn';
- config.filebrowserBrowseUrl = 'ckeditor/uploader/browse.jsp';
- config.filebrowserImageBrowseUrl = 'ckeditor/uploader/browse.jsp?type=Images';
- config.filebrowserFlashBrowseUrl = 'ckeditor/uploader/browse.jsp?type=Flashs';
- config.filebrowserUploadUrl = 'ckeditor/uploader/upload.jsp';
- config.filebrowserImageUploadUrl = 'ckeditor/uploader/upload.jsp?type=Images';
- config.filebrowserFlashUploadUrl = 'ckeditor/uploader/upload.jsp?type=Flashs';
- config.filebrowserWindowWidth = '640';
- config.filebrowserWindowHeight = '480';
- }
CKEDITOR.editorConfig = function( config ){config.language = 'zh-cn';config.filebrowserBrowseUrl = 'ckeditor/uploader/browse.jsp';config.filebrowserImageBrowseUrl = 'ckeditor/uploader/browse.jsp?type=Images';config.filebrowserFlashBrowseUrl = 'ckeditor/uploader/browse.jsp?type=Flashs';config.filebrowserUploadUrl = 'ckeditor/uploader/upload.jsp';config.filebrowserImageUploadUrl = 'ckeditor/uploader/upload.jsp?type=Images';config.filebrowserFlashUploadUrl = 'ckeditor/uploader/upload.jsp?type=Flashs';config.filebrowserWindowWidth = '640';config.filebrowserWindowHeight = '480';}
OK,修改完畢。簡單吧,其實上傳和瀏覽檔案很簡單(上面只是一個示範,代碼僅供參考),要點是要調用一下CKEDITOR.tools.callFunction方法。
附件打包了一個可啟動並執行Eclipse工程,供需要的朋友參考。
---------------------------------------------------------------------------------------
圖片預覽:
檔案夾結構
上傳效果: