CKEditor的編輯器工具欄中有一項「圖片域」,該工具能夠貼上圖片地址來在文本編輯器中加入圖片,可是沒有圖片上傳。javascript

「預覽」中有一大堆鳥語,看得很不爽。能夠打開ckeditor/plugins/image/dialogs/image.js文件,搜索「b.config.image_previewText」就能找到這段鳥語了,(b.config.image_previewText||'')單引號中的內容全刪了,注意別刪多了。html
掃除這個障礙,下面來研究圖片上傳。java
step 1:apache
首先,仍是image.js這個文件,搜索「upload」能夠找到這一段服務器
id:'Upload',hidden:truedom
實際上上傳功能被隱藏了,把上面的true改爲false,再打開編輯器,就能找到上傳功能了。編輯器

step 2:ide
上面的只是一個上傳頁面。也就至關於一個HTML的form表單,要配置點擊「上傳到服務器上」按鈕後請求的Action。能夠在ckeditor/config.js中配置。工具
加入:post
config.filebrowserUploadUrl="actions/ckeditorUpload";
"ckeditorUpload"是請求的URL,也就是點擊這個按鈕就會post到ckeditorUpload地址進行處理,這裏指向的是Struts 2的一個Action。固然,也能夠用servlet或者ASP、PHP等來處理請求。
- <package name="actions" extends="struts-default" namespace="/actions">
- <action name="ckeditorUpload" class="com.xxx.CkeditorUpload ">
- </action>
- </package>
step 3:
文件上傳的控件至關於<input type="file" name="upload" .../>,其name是」upload」,知道了name那麼就能夠在Action中獲取這個文件。
- private File upload;
- private String uploadContentType;
- private String uploadFileName;
以上三個私有變量都要有set方法。若是不瞭解的話能夠先學習一下Struts 2文件上傳。
step 4:
若是上傳的圖片格式不正確,能夠在上傳界面進行提示。

這個提示不是ckeditor提示的,要在Action中響應。
- String callback = ServletActionContext.getRequest().getParameter("CKEditorFuncNum");
- if([判斷條件]){
- out.println("<script type=\"text/javascript\">");
- out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件格式不正確(必須爲.jpg/.gif/.bmp/.png文件)');");
- out.println("</script>");
- return null;
- }
step 5:
- InputStream is = new FileInputStream(upload);
- String uploadPath = ServletActionContext.getServletContext().getRealPath("/img/postImg");
- String fileName = java.util.UUID.randomUUID().toString();
- fileName += expandedName;
- File toFile = new File(uploadPath, fileName);
- OutputStream os = new FileOutputStream(toFile);
- byte[] buffer = new byte[1024];
- int length = 0;
- while ((length = is.read(buffer)) > 0) {
- os.write(buffer, 0, length);
- }
- is.close();
- os.close();
這段代碼是Struts 2上傳圖片的核心代碼,把圖片上傳後保存在項目的某個目錄下,並隨機重命名。
step 6:
圖片上傳成功,在目錄下也能夠看到圖片,至此圖片上傳成功。可是如何將圖片發到編輯器中呢?
點「肯定」按鈕會有如下提示。

到這裏,要在Action中返回一段JS腳本。
- String callback =ServletActionContext.getRequest().getParameter("CKEditorFuncNum");
- out.println("<script type=\"text/javascript\">");
- out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" +"img/postImg/"+ fileName + "','')");
- out.println("</script>");
有了這段代碼,圖片上傳成功後,根據這裏的
"img/postImg/" + filename
相對地址,就能夠使用這個圖片,直接轉到「圖像」頁面。

附:Struts 2 Action代碼