富文本編輯器 CKeditor 配置使用+上傳圖片

来源:https://www.cnblogs.com/wuling129/archive/2018/01/11/8268440.html
-Advertisement-
Play Games

參考文獻: 富文本編輯器 CKeditor 配置使用 CKEditor與CKFinder的配置(ASP.NET環境),老版本可以參考 CKEditor+CKFinder ASP版在本地電腦中的配置 有點問題 富文本文件CKEDITOR增加上傳圖片功能(.net),ckeditor上傳圖片 發現可行 ...


參考文獻:

富文本編輯器 CKeditor 配置使用

CKEditor與CKFinder的配置(ASP.NET環境),老版本可以參考

CKEditor+CKFinder ASP版在本地電腦中的配置  有點問題

富文本文件CKEDITOR增加上傳圖片功能(.net),ckeditor上傳圖片  發現可行

 

富文本編輯器 CKeditor 配置使用+上傳圖片

Ckeditor下載地址:http://ckeditor.com/download

下載後預設放在網站根目錄下 ckeditor文件夾中

一、使用方法:
1、在頁面<head>中引入ckeditor核心文件ckeditor.js

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

2、在使用編輯器的地方插入HTML控制項<textarea>

<textarea id="TextArea1" cols="20" rows="2" class="ckeditor"></textarea>

如果是ASP.NET環境,也可用伺服器端控制項<TextBox>

<asp:TextBox ID="tbContent" runat="server" TextMode="MultiLine" class="ckeditor"></asp:TextBox>

註意在控制項中加上 class="ckeditor" 。

3、將相應的控制項替換成編輯器代碼

<script type="text/javascript">
    CKEDITOR.replace('TextArea1');
    //如果是在ASP.NET環境下用的伺服器端控 件<TextBox>
    CKEDITOR.replace('tbContent');
    //如 果<TextBox>控制項在母版頁中,要這樣寫
    CKEDITOR.replace('<%=tbContent.ClientID.Replace("_","$") %>');
</script>

4、配置編輯器

    ckeditor的配置都集中在 ckeditor/config.js 文件中,下麵是一些常用的配置參數:

// 界面語言,預設為 'en'
    config.language = 'zh-cn';
    // 設置寬高
    config.width = 400;
    config.height = 400;
    // 編輯器樣式,有三種:'kama'(預設)、'office2003'、'v2'
    config.skin = 'v2';
    // 背景顏色
    config.uiColor = '#FFF';
    // 工具欄(基礎'Basic'、全能'Full'、自定義)plugins/toolbar/plugin.js
    config.toolbar = 'Basic';
    config.toolbar = 'Full';
    這將配合:
    config.toolbar_Full = [
       ['Source','-','Save','NewPage','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'],
       ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
       '/',
        ['Styles','Format','Font','FontSize'],
        ['TextColor','BGColor']
    ];
    //工具欄是否可以被收縮
    config.toolbarCanCollapse = true;
    //工具欄的位置
    config.toolbarLocation = 'top';//可選:bottom
    //工具欄預設是否展開
    config.toolbarStartupExpanded = true;
    // 取消 “拖拽以改變尺寸”功能 plugins/resize/plugin.js
    config.resize_enabled = false;
    //改變大小的最大高度
    config.resize_maxHeight = 3000;
    //改變大小的最大寬度
    config.resize_maxWidth = 3000;
    //改變大小的最小高度
    config.resize_minHeight = 250;
    //改變大小的最小寬度
    config.resize_minWidth = 750;
    // 當提交包含有此編輯器的表單時,是否自動更新元素內的數據
    config.autoUpdateElement = true;
    // 設置是使用絕對目錄還是相對目錄,為空為相對目錄
    config.baseHref = ''
    // 編輯器的z-index值
    config.baseFloatZIndex = 10000;
    //設置快捷鍵
    config.keystrokes = [
       [ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ],  //獲取焦點
        [ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ],  //元素焦點
       [ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ],  //文本菜單
       [ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ],  //撤銷
        [ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ],  //重做
        [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ],  //
        [ CKEDITOR.CTRL + 76 /*L*/, 'link' ],  //鏈接
        [ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],  //粗體
        [ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],  //斜體
        [ CKEDITOR.CTRL + 85 /*U*/, 'underline' ],  //下劃線
        [ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]
    ]
    //設置快捷鍵 可能與瀏覽器快捷鍵衝突 plugins/keystrokes/plugin.js.
    config.blockedKeystrokes = [
        CKEDITOR.CTRL + 66 /*B*/,
        CKEDITOR.CTRL + 73 /*I*/,
        CKEDITOR.CTRL + 85 /*U*/
    ]
    //設置編輯內元素的背景色的取值 plugins/colorbutton/plugin.js.
    config.colorButton_backStyle = {
        element : 'span',
        styles : { 'background-color' : '#(color)' }
    }
    //設置前景色的取值 plugins/colorbutton/plugin.js
    config.colorButton_colors = '000,800000,8B4513,2F4F4F,008080,000080,4B0082,696969,B22222,A52A2A,DAA520,006400,40E0D0,0000CD,800080,808080,F00,FF8C00,FFD700,008000,0FF,00F,EE82EE,A9A9A9,FFA07A,FFA500,FFFF00,00FF00,AFEEEE,ADD8E6,DDA0DD,D3D3D3,FFF0F5,FAEBD7,FFFFE0,F0FFF0,F0FFFF,F0F8FF,E6E6FA,FFF’

    //是否在選擇顏色時顯示“其它顏色”選項 plugins/colorbutton/plugin.js
    config.colorButton_enableMore = false
    //區塊的前景色預設值設置 plugins/colorbutton/plugin.js
    config.colorButton_foreStyle = {
        element : 'span',
        styles : { 'color' : '#(color)' }
    };
    //所需要添加的CSS文件 在此添加 可使用相對路徑和網站的絕對路徑
    config.contentsCss = './contents.css';
    //文字方向
    config.contentsLangDirection = 'rtl'; //從左到右
    //CKeditor的配置文件 若不想配置 留空即可
    CKEDITOR.replace( 'myfiled', { customConfig : './config.js' } );
    //界面編輯框的背景色 plugins/dialog/plugin.js
    config.dialog_backgroundCoverColor = '#fffefd'; //可設置參考
    config.dialog_backgroundCoverColor = 'white' //預設
    //背景的不透明度 數值應該在:0.0~1.0 之間 plugins/dialog/plugin.js
    config.dialog_backgroundCoverOpacity = 0.5
    //移動或者改變元素時 邊框的吸附距離 單位:像素 plugins/dialog/plugin.js
    config.dialog_magnetDistance = 20;
    //是否拒絕本地拼寫檢查和提示 預設為拒絕 目前僅firefox和safari支持 plugins/wysiwygarea/plugin.js.
    config.disableNativeSpellChecker = true
    //進行表格編輯功能 如:添加行或列 目前僅firefox支持 plugins/wysiwygarea/plugin.js
    config.disableNativeTableHandles = true; //預設為不開啟
    //是否開啟 圖片和表格 的改變大小的功能 config.disableObjectResizing = true;
    config.disableObjectResizing = false //預設為開啟
    //設置HTML文檔類型
    config.docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22' ;
    //是否對編輯區域進行渲染 plugins/editingblock/plugin.js
    config.editingBlock = true;
    //編輯器中回車產生的標簽
    config.enterMode = CKEDITOR.ENTER_P; //可選:CKEDITOR.ENTER_BR或CKEDITOR.ENTER_DIV
    //是否使用HTML實體進行輸出 plugins/entities/plugin.js
    config.entities = true;
    //定義更多的實體 plugins/entities/plugin.js
    config.entities_additional = '#39'; //其中#代替了&
    //是否轉換一些難以顯示的字元為相應的HTML字元 plugins/entities/plugin.js
    config.entities_greek = true;
    //是否轉換一些拉丁字元為HTML plugins/entities/plugin.js
    config.entities_latin = true;
    //是否轉換一些特殊字元為ASCII字元 如"This is Chinese: 漢語."轉換為"This is Chinese: 漢語." plugins/entities/plugin.js
    config.entities_processNumerical = false;
    //添加新組件
    config.extraPlugins = 'myplugin'; //非預設 僅示例
    //使用搜索時的高亮色 plugins/find/plugin.js
    config.find_highlight = {
        element : 'span',
        styles : { 'background-color' : '#ff0', 'color' : '#00f' }
    };
    //預設的字體名 plugins/font/plugin.js
    config.font_defaultLabel = 'Arial';
    //字體編輯時的字元集 可以添加常用的中文字元:宋體、楷體、黑體等 plugins/font/plugin.js
    config.font_names = 'Arial;Times New Roman;Verdana';
    //文字的預設式樣 plugins/font/plugin.js
    config.font_style = {
        element   : 'span',
        styles   : { 'font-family' : '#(family)' },
        overrides : [ { element : 'font', attributes : { 'face' : null } } ]
    };
    //字體預設大小 plugins/font/plugin.js
    config.fontSize_defaultLabel = '12px';
    //字體編輯時可選的字體大小 plugins/font/plugin.js
    config.fontSize_sizes ='8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px'
    //設置字體大小時 使用的式樣 plugins/font/plugin.js
    config.fontSize_style = {
        element   : 'span',
        styles   : { 'font-size' : '#(size)' },
        overrides : [ { element : 'font', attributes : { 'size' : null } } ]
    };
    //是否強制複製來的內容去除格式 plugins/pastetext/plugin.js
    config.forcePasteAsPlainText =false //不去除
    //是否強制用“&”來代替“&amp;”plugins/htmldataprocessor/plugin.js
    config.forceSimpleAmpersand = false;
    //對address標簽進行格式化 plugins/format/plugin.js
    config.format_address = { element : 'address', attributes : { class : 'styledAddress' } };
    //對DIV標簽自動進行格式化 plugins/format/plugin.js
    config.format_div = { element : 'div', attributes : { class : 'normalDiv' } };
    //對H1標簽自動進行格式化 plugins/format/plugin.js
    config.format_h1 = { element : 'h1', attributes : { class : 'contentTitle1' } };
    //對H2標簽自動進行格式化 plugins/format/plugin.js
    config.format_h2 = { element : 'h2', attributes : { class : 'contentTitle2' } };
    //對H3標簽自動進行格式化 plugins/format/plugin.js
    config.format_h1 = { element : 'h3', attributes : { class : 'contentTitle3' } };
    //對H4標簽自動進行格式化 plugins/format/plugin.js
    config.format_h1 = { element : 'h4', attributes : { class : 'contentTitle4' } };
    //對H5標簽自動進行格式化 plugins/format/plugin.js
    config.format_h1 = { element : 'h5', attributes : { class : 'contentTitle5' } };
    //對H6標簽自動進行格式化 plugins/format/plugin.js
    config.format_h1 = { element : 'h6', attributes : { class : 'contentTitle6' } };
    //對P標簽自動進行格式化 plugins/format/plugin.js
    config.format_p = { element : 'p', attributes : { class : 'normalPara' } };
    //對PRE標簽自動進行格式化 plugins/format/plugin.js
    config.format_pre = { element : 'pre', attributes : { class : 'code' } };
    //用分號分隔的標簽名字 在工具欄上顯示 plugins/format/plugin.js
    config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre;address;div';
    //是否使用完整的html編輯模式 如使用,其源碼將包含:<html><body></body></html>等標簽
    config.fullPage = false;
    //是否忽略段落中的空字元 若不忽略 則字元將以“”表示 plugins/wysiwygarea/plugin.js
    config.ignoreEmptyParagraph = true;
    //在清除圖片屬性框中的鏈接屬性時 是否同時清除兩邊的<a>標簽 plugins/image/plugin.js
    config.image_removeLinkByEmptyURL = true;
    //一組用逗號分隔的標簽名稱,顯示在左下角的層次嵌套中 plugins/menu/plugin.js.
    config.menu_groups ='clipboard,form,tablecell,tablecellproperties,tablerow,tablecolumn,table,anchor,link,image,flash,checkbox,radio,textfield,hiddenfield,imagebutton,button,select,textarea';
    //顯示子菜單時的延遲,單位:ms plugins/menu/plugin.js
    config.menu_subMenuDelay = 400;
    //當執行“新建”命令時,編輯器中的內容 plugins/newpage/plugin.js
    config.newpage_html = '';
    //當從word里複製文字進來時,是否進行文字的格式化去除 plugins/pastefromword/plugin.js
    config.pasteFromWordIgnoreFontFace = true; //預設為忽略格式
    //是否使用<h1><h2>等標簽修飾或者代替從word文檔中粘貼過來的內容 plugins/pastefromword/plugin.js
    config.pasteFromWordKeepsStructure = false;
    //從word中粘貼內容時是否移除格式 plugins/pastefromword/plugin.js
    config.pasteFromWordRemoveStyle = false;
    //對應後臺語言的類型來對輸出的HTML內容進行格式化,預設為空
    config.protectedSource.push( /<"?["s"S]*?"?>/g );   // PHP Code
    config.protectedSource.push( //g );   // ASP Code
    config.protectedSource.push( /(]+>["s|"S]*?<"/asp:[^">]+>)|(]+"/>)/gi );   // ASP.Net Code
    //當輸入:shift+Enter時插入的標簽
    config.shiftEnterMode = CKEDITOR.ENTER_P;  //可選:CKEDITOR.ENTER_BR或CKEDITOR.ENTER_DIV
    //可選的表情替代字元 plugins/smiley/plugin.js.
    config.smiley_descriptions = [
        ':)', ':(', ';)', ':D', ':/', ':P',
        '', '', '', '', '', '',
        '', ';(', '', '', '', '',
        '', ':kiss', '' ];
    //對應的表情圖片 plugins/smiley/plugin.js
    config.smiley_images = [
        'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif',
        'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif',
        'devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif',
        'broken_heart.gif','kiss.gif','envelope.gif'];
    //表情的地址 plugins/smiley/plugin.js
    config.smiley_path = 'plugins/smiley/images/';
    //頁面載入時,編輯框是否立即獲得焦點 plugins/editingblock/plugin.js plugins/editingblock/plugin.js.
    config.startupFocus = false;
    //載入時,以何種方式編輯 源碼和所見即所得 "source"和"wysiwyg" plugins/editingblock/plugin.js.
    config.startupMode ='wysiwyg';
    //載入時,是否顯示框體的邊框 plugins/showblocks/plugin.js
    config.startupOutlineBlocks = false;
    //是否載入樣式文件 plugins/stylescombo/plugin.js.
    config.stylesCombo_stylesSet = 'default';
    //以下為可選
    config.stylesCombo_stylesSet = 'mystyles';
    config.stylesCombo_stylesSet = 'mystyles:/editorstyles/styles.js';
    config.stylesCombo_stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
    //起始的索引值
    config.tabIndex = 0;
    //當用戶鍵入TAB時,編輯器走過的空格數,(&nbsp;) 當值為0時,焦點將移出編輯框 plugins/tab/plugin.js
    config.tabSpaces = 0;
    //預設使用的模板 plugins/templates/plugin.js.
    config.templates = 'default';
    //用逗號分隔的模板文件plugins/templates/plugin.js.
    config.templates_files = [ 'plugins/templates/templates/default.js' ]
    //當使用模板時,“編輯內容將被替換”框是否選中 plugins/templates/plugin.js
    config.templates_replaceContent = true;
    //主題
    config.theme = 'default';
    //撤銷的記錄步數 plugins/undo/plugin.js
    config.undoStackSize =20;
    // 在 CKEditor 中集成 CKFinder,註意 ckfinder 的路徑選擇要正確。
    //CKFinder.SetupCKEditor(null, '/ckfinder/');

 

二、 一些使用技巧
1、在頁面中即時設置編輯器

<script type="text/javascript">
        // 示例1:設置工具欄為基本工具欄,高度為70
        CKEDITOR.replace('<%=tbLink.ClientID.Replace("_","$") %>',
        { toolbar:'Basic', height:70 });
        //示例2:工具欄為自定義類型
        CKEDITOR.replace( 'editor1',
        {
             toolbar :
             [
                //加粗     斜體,     下劃線      穿過線      下標字        上標字
                ['Bold','Italic','Underline','Strike','Subscript','Superscript'],
                // 數字列表          實體列表            減小縮進    增大縮進
                ['NumberedList','BulletedList','-','Outdent','Indent'],
                //左對 齊             居中對齊          右對齊          兩端對齊
                ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                //超鏈接  取消超鏈接 錨點
                ['Link','Unlink','Anchor'],
                //圖片    flash    表格       水平線            表情       特殊字元        分頁符
                ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
                '/',
                // 樣式       格式      字體    字體大小
                ['Styles','Format','Font','FontSize'],
                //文本顏色     背景顏色
                ['TextColor','BGColor'],
                //全屏           顯示區塊
                ['Maximize', 'ShowBlocks','-']
             ]
        }
    );
</script>

 

三、精簡ckeditor
    在部署到Web伺服器上時,下列文件夾和文件都可以刪除:
    /_samples :示例文件夾;
    /_source :未壓縮源程式;
    /lang文件夾下除 zh-cn.js、en.js 以外的文件(也可以根據需要保留其他語言文件);
    根目錄下的 changes.html(更新列表),install.html(安裝指向),license.html(使用許可);
    /skins 目錄下不需要的皮膚,一般用V2(簡單,朴素) ,如果只保留V2則必須在config.js中指定皮膚。

四, 版本問題

    在CKEditor的官方網站上下載,最要下載全部功能,最後得到的壓縮包是ckeditor_4.1.1_full.zip,如果選擇simple或者standed,可能會有些功能不能用,比如字體顏色,背景顏色,這下功能在standed版本裡面就不支持。所以你會很奇怪明明設置了['TextColor','BGColor'],但是文本顏色和背景顏色選項就是不顯示。

五,去掉預設的段落標記

去除CKEditor自動添加的<p></p>標簽的方法,其實很簡單,有兩種辦法:

1.在ckeditor目錄下的config.js添加以下配置參數即可:

config.enterMode = CKEDITOR.ENTER_BR:  屏蔽換行符<br>
config.shiftEnterMode = CKEDITOR.ENTER_P:屏蔽段落<p>

2.直接更改編輯器預設模式為源代碼模式,在ckeditor目錄下的config.js添加以下配置:

config.startupMode = 'source';

六,和kcfinder搭配使用實現圖片上傳

老版本可以參考:CKEditor與CKFinder的配置(ASP.NET環境)

但是實際應用發現不行,新版本已經發生改變。

後來參考:CKEditor+CKFinder ASP版在本地電腦中的配置 發現也不行,設置如下:

第四步配置CKEditor下的config.js文件:

下麵的路徑都要帶上根目錄(zhongyuan);

 config.filebrowserBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html';
 config.filebrowserImageBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html?Type=Images';
 config.filebrowserFlashBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html?Type=Flash';
 config.filebrowserUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Files';
 config.filebrowserImageUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Images';
 config.filebrowserFlashUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Flash';

//此代碼為啟用上傳圖片的功能

但是下載的CKFinder 根本就沒有core目錄,提示找不到文件:無語!這個要收費!好吧!再想辦法!

參考:富文本文件CKEDITOR增加上傳圖片功能(.net),ckeditor上傳圖片  發現可行!

七、 CKEDITOR增加上傳圖片功能(.net)

第一種方法使用CKEDITOR自身代碼功能

“預覽”中有一大堆鳥語,看得很不爽。可以使用1或2來進行清除。

1:可以打開ckeditor/plugins/image/dialogs/image.js文件,搜索“b.config.image_previewText”就能找到這段鳥語了,(b.config.image_previewText||'')單引號中的內容全刪了,註意別刪多了。

2:打開ckeditor/config.js文件,在此函數內,添加

config.image_previewText = ''; //清空預覽區域顯示內容

 打開ckeditor/plugins/image/dialogs/image.js文件,搜索“upload”可以找到這一段

 id:'Upload',hidden:true

 實際上上傳功能被隱藏了,把上面的true改成false,如果你的顯示是hidden:!0,直接改成0即可,就可以顯示了,再打開編輯器,就能找到上傳功能了。

設置上傳到伺服器按鈕的事件URL,指定將上傳的文件提交給那個URL進行處理,

打開ckeditor/config.js文件,在此函數內,添加

 config.filebrowserImageUploadUrl = '../UploadImgHandler.ashx';//設置提交上傳圖片按鈕處理URL,我這裡設置的提交給一個一般處理程式,這個是自己要創建的,我的是創建到根目錄的,所以會有../,好了,下麵開始編寫UploadImgHandler.ashx'文件內的代碼吧,如下:

public void ProcessRequest(HttpContext context)
    {
        String callback = context.Request.QueryString["CKEditorFuncNum"].ToString();
        ///'遍歷File表單元素
        HttpFileCollection files = HttpContext.Current.Request.Files;
        for (int iFile = 0; iFile < files.Count; iFile++)
        {
            //    ///'檢查文件擴展名字
            HttpPostedFile postedFile = files[iFile];
            //HttpPostedFile postedFile = files[0];
            string fileName;   //, fileExtension
            fileName = System.IO.Path.GetFileName(postedFile.FileName);


            string fileContentType = postedFile.ContentType.ToString();
            if (fileContentType == "image/bmp" || fileContentType == "image/gif" ||
                fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg"
                || fileContentType == "image/pjpeg")
            {
                if (postedFile.ContentLength <= 2097152)
                {
                    string filepath = postedFile.FileName;      //得到的是文件的完整路徑,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg 
                    //string filepath = FileUpload1.FileName;               //得到上傳的文件名20022775_m.jpg 

                    string serverpath = context.Server.MapPath("~/UpLoadFile/ImageUpload/") + fileName;//取得文件在伺服器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg 

                    postedFile.SaveAs(serverpath);//上傳圖片到伺服器指定地址

                    string imageurl = "http://localhost:13392/UpLoadFile/ImageUpload/" + fileName;//我是將測試時的本地地址+放置圖像的文件夾+圖片名稱作為返回的URL

                    // 返回"圖像"選項卡並顯示圖片 
                    context.Response.Write("<script type=\"text/javascript\">");
                    context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + callback
                           + ",'" + imageurl + "','')");
                    context.Response.Write("</script>");
                }
                else
                {
                    context.Response.Write("<script>alert('上傳文件不能大於2M!')</script>");
                }
            }
            else
            {
                context.Response.Write("<script>alert('只支持BMP、GIF、JPG、PNG格式的圖片!')</script>");
            }
        }
    }

好了,可以上傳圖片了!哈哈!剩下的方法還沒有實驗,保留下來,留待研究!

好了,以上是使用CKEDITOR自身的上傳功能,外加一個一般處理程式來完成上傳功能。

第二種設置上傳功能方法:如果你已經有了自己的上傳模板(我指的是一個單獨的上傳網頁),

 

打開ckeditor/plugins/image/dialogs/image.js文件,搜索“urlMissing”可以找到這一段,在},之後添加如下代碼:

{ type: 'button', id: 'myUpload', style:"margin-top:14px;", align: 'center', label: '本地上傳', onClick: function () { var retFile = showModalDialog("../UpLoadWeixinImg.aspx", "", "dialogHeight:380;dialogWidth:600;"); if (retFile != null) { this.getDialog().setValueOf('info', 'txtUrl', retFile); } } },

showModalDialog("../UpLoadWeixinImg.aspx",指定轉向URL的鏈接地址,上傳模板,showModalDialog方法在IE和火狐下能正常運行,在谷歌瀏覽器下可能不相容,反正我試了不行,聽說用window.open可以代替,我沒有去嘗試,您可以去試下,

 

下麵來看看UpLoadWeixinImg.aspx上傳頁面模板的代碼如下:

 

/// <summary>
        /// 上傳圖片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkBtnFileUploadImg_Click(object sender, EventArgs e)
        {
            if (this.FileUploadImg.HasFile)
            {
                string fileContentType = FileUploadImg.PostedFile.ContentType;
                if (fileContentType == "image/bmp" || fileContentType == "image/gif"||
                    fileContentType == "image/png"|| fileContentType == "image/x-png"|| fileContentType == "image/jpeg"
                    || fileContentType == "image/pjpeg")
                {
                    int fileSize = this.FileUploadImg.PostedFile.ContentLength;

                    if (fileSize <= 2097152)
                    {
                        string fileName = this.FileUploadImg.PostedFile.FileName;                  // 客戶端文件路徑

                        string imageurl = "http://localhost:8665/WeiXinImg/" + fileName;

                        string filepath = FileUploadImg.PostedFile.FileName;  //得到的是文件的完整路徑,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg 
                        //string filepath = FileUpload1.FileName;               //得到上傳的文件名20022775_m.jpg 
                        string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg 
                        string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在伺服器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg 
                        this.FileUploadImg.PostedFile.SaveAs(serverpath);//將上傳的文件另存為

         //此處我調用的是前臺客戶端的js腳本
                        ClientScript.RegisterStartupScript(this.GetType(), "SayHello", "<script>SayHello('" + imageurl + "')</script>");
                    }
                    else
                    {
                        Response.Write("<script>alert('上傳文件不能大於2M!')</script>");
                    }

                }
                else
                {
                    Response.Write("<script>alert('只支持BMP、GIF、JPG、PNG格式的圖片!')</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('請選擇圖片!')</script>");
            }
        }

 

SayHello腳本如下:

 <script type="text/javascript">
        function SayHello(imgPath) {
            window.returnValue = imgPath; //上傳後的圖片鏈接
            window.close();
        }
</script>

兩種方式實現方式一樣,具體哪個好用可以根據需要選擇!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • mysql+ef的配置相比較mssql+ef來說複雜一些。我的感受就是配置難度在於插件版本造成的各種不相容問題。另外參考了很多博客,將多個博客里的經驗綜合才得以實現,因為不是每個人的操作都和那些博客作者描述的情況一致,不過解決之後其他都好說。現在從零開始操作mysql+CodeFirst的實現,總結 ...
  • 【轉】《深入理解C# 3.x的新特性》博文系列彙總 較之C# 2.0, C# 3.x引入了一系列新的特性,為我們編程帶來很大的便利,通過有效地利用這些新特性,我們可以編寫出更加簡潔、優雅的程式。不過這些新特性僅僅是編譯器給我們耍的小花招:在編譯的時候加入一些必要的Code,使這些在C# 2.0角度看 ...
  • 目錄: WPF自定義Window樣式(1) WPF自定義Window樣式(2) 1. 引言 在上一篇中,介紹瞭如何建立自定義窗體。接下來,我們需要考慮將該自定義窗體基類放到類庫中去,只有放到類庫中,我們才能在其他地方去方便的引用該基類。 2. 創建類庫 接上一篇的項目,先添加一個類庫項目stonem ...
  • 目的:只允許同級拖動。 兩個判斷: 1.原節點(假設為:S)的父級如果不等於目標節點(假設為:T)的父節點,那麼發生了跨級,即非同級移動。這個判斷很容易。 2.S、T是同一級的,但是S是移動到T下一級,這種情景下,移動過程中,S和T的父節點是一致的,不能判斷是否跨級移動,那麼怎麼辦判斷呢? 方案1: ...
  • 泛型概述 泛型是程式設計語言的一種特性。允許程式員在強類型程式設計語言中編寫代碼時定義一些可變部分,那些部分在使用前必須作出指明。各種程式設計語言和其編譯器、運行環境對泛型的支持均不一樣。將類型參數化以達到代碼復用提高軟體開發工作效率的一種數據類型。泛型類是引用類型,是堆對象,主要是引入了類型參數這 ...
  • 一. 準備工作 1. 點擊此下載支持.Net4.0的 FastReport ,安裝後並破解 2. VS2012 工具箱中,新建選項卡,添加 %安裝目錄%\Framework 4.0\FastReport.dll 選項 可在選項卡下查看到如下圖,表示整合成功 二. 相關文件介紹 1. 在 %當前用戶% ...
  • 目錄: WPF自定義Window樣式(1) WPF自定義Window樣式(2) 1. 引言 WPF是製作界面的一大利器。最近在做一個項目,用的就是WPF。既然使用了WPF了,那麼理所當然的,需要自定義窗體樣式。所使用的代碼是在網上查到的,遺憾的是,整理完畢後,再找那篇帖子卻怎麼也找不到了,僅僅在下載 ...
  • 例子: 給佈局內動態添加一個panel,給panel一個id,加內容的時候加到這個id里就可以了 html: ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...