使用Kindeditor上傳圖片,kindeditor上傳圖片
給客戶製作的項目中需要添加富文本,從網上看了一下很多人推薦kindeditor這個編輯器,用了之後也感覺不錯,有一些問題的就是上傳圖片的時候遇到了一些問題,在這裡記錄一下,也方便以後查看。
首先在官網下載kindeditor壓縮包,(我這裡用的是kindedito-4.1.7),解壓開,把jsp、 plugins、skins、kindeditor.js 、kindedditor-min.js放進自己的項目中(我是放在webroot下面建立的檔案夾kindeditor下面的),其他的可以不放。
下載的壓縮包中有demo我們可以參考一下,upload_json.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="java.util.*,java.io.*" %><%@ page import="java.text.SimpleDateFormat" %><%@ page import="org.apache.commons.fileupload.*" %><%@ page import="org.apache.commons.fileupload.disk.*" %><%@ page import="org.apache.commons.fileupload.servlet.*" %><%@ page import="org.json.simple.*" %><%//檔案儲存目錄路徑String savePath = pageContext.getServletContext().getRealPath("/") + "attached/";//檔案儲存目錄URLString saveUrl = request.getContextPath() + "/attached/";//定義允許上傳的副檔名HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");//最大檔案大小long maxSize = 1000000;response.setContentType("text/html; charset=UTF-8");if(!ServletFileUpload.isMultipartContent(request)){ out.println(getError("請選擇檔案。")); return;}//檢查目錄File uploadDir = new File(savePath);if(!uploadDir.isDirectory()){ out.println(getError("上傳目錄不存在。")); return;}//檢查目錄寫入權限if(!uploadDir.canWrite()){ out.println(getError("上傳目錄沒有寫入權限。")); return;}String dirName = request.getParameter("dir");if (dirName == null) { dirName = "image";}if(!extMap.containsKey(dirName)){ out.println(getError("目錄名不正確。")); return;}//建立檔案夾savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath);if (!saveDirFile.exists()) { saveDirFile.mkdirs();}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) { dirFile.mkdirs();}FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");List items = upload.parseRequest(request);Iterator itr = items.iterator();while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); long fileSize = item.getSize(); if (!item.isFormField()) { //檢查檔案大小 if(item.getSize() > maxSize){ out.println(getError("上傳檔案大小超過限制。")); return; } //檢查副檔名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){ out.println(getError("上傳副檔名是不允許的副檔名。\n只允許" + extMap.get(dirName) + "格式。")); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try{ File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); }catch(Exception e){ out.println(getError("上傳檔案失敗。")); return; } JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); out.println(obj.toJSONString()); }}%><%!private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString();}%>
在我們使用kindeditor的頁面添加如下代碼,其中item是選項卡,這雷根據自己的需要添加選項。
<script charset="utf-8" src="../js/kindeditor-4.1.7/kindeditor.js"></script><script charset="utf-8" src="../js/kindeditor-4.1.7/lang/zh_CN.js"></script>KindEditor.ready(function(K) { window.editor = K.create('#editor_id', { items : ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about'],afterChange : function() {this.sync();} } ); });
然後修改Plugins——>image——>image.js
將其中的
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
修改為
uploadJson = K.undef(self.uploadJson, self.basePath + 'jsp/upload_json.jsp'),
最後不要忘記在我們tomcat目錄下建立一個名為attached的目錄來存放我們的圖片。之所以取名為attached是因為在upload_json.jsp中預設儲存圖片的檔案夾名為attached。自己的這個方法也是摸索著來,希望能夠和大家交流。