struts2下kindeditor編輯器使用

導入支持

        <!--導入在線HTML編輯器 -->
        <script type="text/javascript" src="../../editor/kindeditor.js" ></script>
        <script type="text/javascript" src="../../editor/lang/zh_CN.js" ></script>
        <link rel="stylesheet" href="../../editor/themes/default/default.css" />

具體頁面提供textarea

<textarea id="description" name="description" style="width:80%" rows="20"></textarea>

編寫js代碼

                KindEditor.ready(function(K) {
                    window.editor = K.create('#description');
                        allowFileManager:true,
                        uploadJson : '../../image_upload.action',
                        fileManagerJson : '../../image_manage.action'
                    });
                });

語法:K.create(‘#id’,{options}); 參數採用key-value格式
採用items屬性定製工具欄按鈕顯示

{
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', 'multiimage','flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak','anchor', 'link', 'unlink', '|', 'about']
}

使用kindeditor使用圖片上傳編輯顯示功能,需要指定uploadJson和fileManagerJson,默認採用PHP實現,如果使用java實現,需要設置初始化參數

{
allowFileManager:true,
uploadJson : '../../image_upload.action',
fileManagerJson : '../../image_manage.action'
}

在服務器編寫ImageAction,處理kindeditor文件上傳功能

package com.ikayaki.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ikayaki.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class ImageAction extends BaseAction<Object> {
    private static final long serialVersionUID = 1L;
    private File imgFile;
    private String imgFileFileName;
    private String imgFileContentType;

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    @Action(value = "image_upload", results = { @Result(name = "success", type = "json") })
    public String upload() throws IOException {
        System.out.println("文件:" + imgFile);
        System.out.println("文件名:" + imgFileFileName);
        System.out.println("文件類型:" + imgFileContentType);

        String savePath = ServletActionContext.getServletContext().getRealPath(
                "/upload/");
        String saveUrl = ServletActionContext.getRequest().getContextPath()
                + "/upload/";

        // 生成隨機圖片名
        UUID uuid = UUID.randomUUID();
        String ext = imgFileFileName
                .substring(imgFileFileName.lastIndexOf("."));
        String randomFileName = uuid + ext;

        // 保存圖片 (絕對路徑)
        File destFile = new File(savePath + "/" + randomFileName);
        System.out.println(destFile.getAbsolutePath());
        FileUtils.copyFile(imgFile, destFile);

        // 通知瀏覽器文件上傳成功
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("error", 0);
        result.put("url", saveUrl + randomFileName); // 返回相對路徑
        ActionContext.getContext().getValueStack().push(result);

        return SUCCESS;
    }
}

在頁面點擊圖片空間,發送請求image_manage.action

fileManagerJson : '../../image_manage.action'

ImageAction添加manage方法

@Action(value = "image_manage", results = { @Result(name = "success", type = "json") })
    public String manage() {
        // 根目錄路徑,可以指定絕對路徑,比如 d:/xxx/upload/xxx.jpg
        String rootPath = ServletActionContext.getServletContext().getRealPath(
                "/")
                + "upload/";
        // 根目錄URL,可以指定絕對路徑,比如 http://www.yoursite.com/attached/
        String rootUrl = ServletActionContext.getRequest().getContextPath()
                + "/upload/";

        // 遍歷目錄取的文件信息
        List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
        // 當前上傳目錄
        File currentPathFile = new File(rootPath);
        // 圖片擴展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };

        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Map<String, Object> hash = new HashMap<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(
                            fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String> asList(fileTypes)
                            .contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime",
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
                                .lastModified()));
                fileList.add(hash);
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", rootPath);
        result.put("current_url", rootUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        ActionContext.getContext().getValueStack().push(result);

        return SUCCESS;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章