使用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/";

//文件保存目錄URL
String 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。自己的這個方法也是摸索着來,希望能夠和大家交流。

 

作者: 傑瑞教育
出處: http://www.cnblogs.com/jerehedu/ 
本文版權歸煙台傑瑞教育科技有限公司和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM