ckeditor添加自定義按鈕整合swfupload實現批量上傳圖片

ckeditor添加自定義按鈕整合swfupload實現批量上傳圖片
給ckeditor添加自定義按鈕,因爲ckeditor只能上傳一張圖片,若是要上傳多張圖片就要結合ckfinder,而ckfinder是收費的,因此就想經過自定義按鈕整合swfupload實現一次上傳多張圖片的功能
首先下載並安裝ckeditor。
下載swfupload解壓拷貝到對應的文件目錄下
三、自定義工具欄按鈕:
咱們能夠自定義ckeditor工具欄要顯示的按鈕,工具欄按鈕定義能夠參考這裏。
如今咱們須要向工具欄添加一個自定義功能的按鈕。ckeditor工具欄中的每一個按鈕都是做爲插件定義在ckeditor\plugins\ 目錄中。咱們在ckeditor\plugins\中建立一個新文件夾imagedef。在imagedef文件夾內,咱們建立一個plugin.js文件,它的代碼以下:
CKEDITOR.plugins.add(
    "imagedef", {
        requires: ["dialog"], //當按鈕觸發時彈出對話框
        init: function (a) {
            a.addCommand("imagedef", new CKEDITOR.dialogCommand("imagedef"));
            a.ui.addButton(
                "Imagedef", {
                    label: "圖片",
                    command: "imagedef",
                    icon: this.path + "imagedef.gif"
                });
            CKEDITOR.dialog.add("imagedef", this.path + "dialogs/imagedef.js");
        }
    }
);
在上面的代碼中咱們指定自定義按鈕的圖標imagedef.gif,imagedef.gif放在imagedef文件夾中。
在imagedef文件夾下新建一個dialogs目錄,在dialogs目錄下新建一個imagedef.js文件,就是上面代碼調用的imagedef.js文件
CKEDITOR.dialog.add(
    "imagedef",
    function (b)
    {
        return {
            title: "圖片",
            minWidth: 590,
            minHeight: 300,
            contents: [{
                id: "tab1",
                label: "",
                title: "",
                expand: true,
                padding: 0,
                elements: [{
                    type: "html",
                    html: initImageDlgInnerHtml() //對話框中要顯示的內容,這裏的代碼將發在下面
                }]
            }],
            onOk: function () { //對話框點擊肯定的時候調用該函數
                    var D = this;
                    var imes = getCkUploadImages(); //獲取上傳的圖片,用於取路徑,將圖片顯示在富文本編輯框中
                    $(imes).each(function () {
                        D.imageElement = b.document.createElement('img');
                        D.imageElement.setAttribute('alt', '');
                        D.imageElement.setAttribute('_cke_saved_src', $(this).attr("src"));
                        D.imageElement.setAttribute('src', $(this).attr("src"));
                        D.commitContent(1, D.imageElement);
                        if (!D.imageElement.getAttribute('style')) {
                            D.imageElement.removeAttribute('style');
                        }
                        b.insertElement(D.imageElement);
                    });
                },
                onLoad: function () { //對話框初始化時調用
                    initEventImageUpload(); //用於註冊上傳swfupload組件
                },
                onShow: function () {
                    clearCkImageUpload(); //在對話框顯示時做一些特殊處理
                }
        };
    }
);
 
接下來咱們須要註冊imagedef插件。原文中的給出方法是在ckeditor.js中註冊,這會使之後升級新版本遇到困難。提倡使用下面的方法在config.js中註冊自定義插件:
CKEDITOR.editorConfig = function (config) {
    config.toolbar_Full = [
        ['Source', 'Preview', '-', 'Templates'],

        ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'],
        ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
        ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
        '/',
        ['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
        ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['Link', 'Unlink', 'Anchor'],
        ['Imagedef', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
        '/',
        ['Styles', 'Format', 'Font', 'FontSize'],
        ['TextColor', 'BGColor']
    ];
    config.resize_maxWidth = 775;
    config.removePlugins = 'elementspath'; //去掉文本框下面出現body p 等
    config.extraPlugins = "imagedef"; //註冊自定義按鈕
};
 

最後,在ckeditor中顯示自定義按鈕linkbutton,代碼以下:
下面代碼是在頁面上寫的,固然能夠根據本身的需求來定,寫在什麼位置
 

//編輯框初始化上傳圖片的回調----------自定義按鈕插件
//上面有個cke_dialog_start_button_z樣式是根據本身的須要來寫的
function initEventImageUpload() { //對上傳控件的註冊
    ckeditorInitSwfu("ck_fs_upload_progress", "stop_id", "ck_btn_id");
    $("#ck_fs_upload_progress").parent().find("object").css({
        "height": "24px",
        "width": "82px"
    });
    $("#ck_btn_start").mouseover(function () {
        $(this).css({
            "cursor": "hand",
            "background-position": "0 -1179px"
        });
    });
}

function clearCkImageUpload() { //對對話框彈出時做特殊處理
    if ($("#ck_fs_upload_progress").html().indexOf(".jpg") != -1) {
        $("#ck_fs_upload_progress").html("");
    }
    $("#ck_pic_div").html("");
}

function getCkUploadImages() {
    return $("#ck_pic_div").find("img");
}
var ckSwfu; //初始化上傳控件
function ckeditorInitSwfu(progress, btn, spanButtonPlaceHolder) {
    var uploadUrl = "${BasePath}/commodity_com/img/uploadCommodityImg.ihtml?type=1";
    //在firefox、chrome下,上傳不能保留登陸信息,因此必須加上jsessionid。
    var jsessionid = $.cookie("JSESSIONID");
    if (jsessionid) {
        uploadUrl += "?jsessionid=" + jsessionid;
    }
    ckSwfu = new SWFUpload({
        upload_url: uploadUrl,
        flash_url: "${BasePath}/res/base/plugin/swfupload/swfupload.swf",
        file_size_limit: "4 MB",
        file_types: "*.jpg;*.png;*.gif;*.jpeg;*.bmp",
        file_types_description: "Web Image Files",
        file_queue_limit: 0,
        custom_settings: {
            progressTarget: progress,
            cancelButtonId: btn
        },
        debug: false,
        button_image_url: "${BasePath}/res/base/plugin/swfupload/button_notext.png",
        button_placeholder_id: spanButtonPlaceHolder,
        button_text: "<span class='btnText'>上傳圖片</span>",
        button_width: 81,
        button_height: 24,
        button_text_top_padding: 2,
        button_text_left_padding: 20,
        button_text_style: '.btnText{color:#666666;}',
        button_cursor: SWFUpload.CURSOR.HAND,
        file_queued_handler: fileQueuedCk,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogCompleteCk,
        upload_start_handler: uploadStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccessCk,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete
    });
};

//開始上傳圖片
function ckUploadImageStart(obj) {
    ckSwfu.startUpload();
}

//回調重寫
function fileQueuedCk(file) {
    try {
        if ($("#ck_fs_upload_progress").html().indexOf(".jpg") == -1) {
            $("#ck_fs_upload_progress").html("");
        }
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("Pending...");
        progress.toggleCancel(true, this);
        $(progress.fileProgressWrapper).css("display", "none");
        $("#ck_fs_upload_progress").append(" " + file.name);

    } catch (ex) {
        this.debug(ex);
    }
}

//回調重寫,上傳成功後
function uploadSuccessCk(file, serverData) {
    try {
        var progress = new FileProgress(file, swfu.customSettings.progressTarget);
        //progress.setComplete();
        //progress.setStatus("上傳成功!");
        //progress.toggleCancel(false);
        $(progress.fileProgressWrapper).css("display", "none");
        var json = eval("(" + serverData + ")");
        var img = '<div style="float:left;"><img picUrl="' + json.url + '" src="${BasePath!'
        '}/' + json.url + '" style="width:80px;height:80px"/><a href="javascript:void(0)" onclick="deletePic(this)">X</a></div>';

        $("#ck_pic_div").append(img);
        $("#ck_pic_div").dragsort("destroy"); //圖片排序,這裏要下載dragsort插件
        $("#ck_pic_div").dragsort({
            dragSelector: "div",
            dragBetween: true,
            placeHolderTemplate: "<div class='placeHolder' style='float:left'><img /><a></a></div>"
        });
    } catch (ex) {}
}

//回調重寫,主要是設置參數,若是須要的參數沒有,就清空上傳的文件,爲了解決下次選擇會上傳沒有參數時的圖片
function fileDialogCompleteCk(numFilesSelected, numFilesQueued) {
    try {

        var commoNo = $("#commoNo").val();
        var brandNo = $("#brand option:selected").val();
        var catNo = $("#thirdCommon option:selected").val();
        //初始化上傳圖片
        if (brandNo != "" && commoNo != "" && catNo != "") {
            this.addPostParam("commoNo", commoNo);
            this.addPostParam("thirdCatNo", catNo);
            this.addPostParam("brandNo", brandNo);
            if (numFilesSelected > 0) {
                document.getElementById(this.customSettings.cancelButtonId).disabled = false;
            }
        } else {
            for (var i = 0; i < numFilesSelected; i++) {
                var promitId = this.customSettings.progressTarget;
                $("#" + promitId).find("*").remove();
                var fileId = this.getFile().id;
                this.cancelUpload(fileId, false);
            }
            $("#ck_fs_upload_progress").html("");
            alert("請選擇分類和品牌!");
        }
    } catch (ex) {
        this.debug(ex);
    }
}javascript

相關文章
相關標籤/搜索