CKEditor 自主控制图片上传

在ASP.NET中使用CKEditor编辑器,如果想控制图片上传,即把上传的图片路径名存到数据中,可以自定义一个上传功能

首先自定义CKEditor的配置文件

在config.js中添加以下代码,红色部分为增加添加图片插件语句

CKEDITOR.editorConfig = function (config) {
    // Define changes to default configuration here. For example:
    config.language = 'zh-cn';
   // config.skin = 'v2';
    config.uiColor = '#AADC6E';
    config.toolbar =
    [
       ['Source', '-', 'Preview', '-'],
        ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
        ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
        '/',
        ['Bold', 'Italic', 'Underline'],
        ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'],
        ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
        ['Link', 'Unlink', 'Anchor'],
        ['addpic', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], //此处的addpic为我们自定义的图标,非CKeditor提供。
        '/',
        ['Styles', 'Format', 'Font', 'FontSize'],
        ['TextColor', 'BGColor'],

    ];


    config.extraPlugins = 'addpic';


};

然后需要为添加图片按钮配置图片

在./ckeditor/plugins/目录下新建一个文件夹addpic,然后在其目录下添加两个文件,一个是名叫addpic.jpg的图片,就是添加图片按钮

的图标,另一个是plugin.js,就是配置此按钮的js代码

plugin.js文件内容

(function () {
    //Section 1 : 按下自定义按钮时执行的代码
    var a = {
        exec: function (editor) {
            show();
        }
    },
    b = 'addpic';
    CKEDITOR.plugins.add(b, {
        init: function (editor) {
            editor.addCommand(b, a);
            editor.ui.addButton('addpic', {
                label: '添加图片',
                icon: this.path + 'addpic.JPG',
                command: b
            });
        }
    });
})();

现在编辑器中已经部署好了添加图片的功能图标,接下来我们就需要完成在点击它时,弹出一个上传文件的对话框,

其中弹出对话框我们使用用jquery开发的popup弹出对话框模式,所以在使用前需要加载相应的js文件

    <script type="text/javascript" src="./Scripts/scripts/jquery.1.3.2.js"></script>
    <script type="text/javascript" src="./Scripts/scripts/popup_layer.js"></script>

    <!--因为我们要把图片加入到编辑其中所以需要通过 CKeditor 的jsAPI来操作,因此也许要加载下面的文件-->
    <script type="text/javascript" src="./ckeditor/ckeditor.js"></script>

    <!--下面的JS文件是需要我们自己写的,就是为了完成图片插入编辑器中-->

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

addimage.js文件内容,也可是将其写在应用编辑器的页面test.aspx中,写成JS文件形式,如果在另个页面也需要此功能只需加载

此文件就行了,不必再复制js代码

function show() {


    $("#ele6")[0].click();
}
function upimg(str) {//上传文件页面上传成功后将返回图片的完整路径名,然后我们就可以将其插入编辑其中


    if (str == "undefined" || str == "") {
        return;
    }
    str = "<img src='" + str + "'></img>";
    CKEDITOR.instances.CKEditor_memo.insertHtml(str);//调用CKEditor的JS接口将图片插入
    close();
}
function close() {


    $("#close6")[0].click();
}
$(document).ready(function () {
    new PopupLayer({ trigger: "#ele6", popupBlk: "#blk6", closeBtn: "#close6", useOverlay: true, offsets: { x: 50, y: 0} });
});

其中应用编辑器的页面test.aspx代码如下

具体如何部署CKEdtior官网上有许多详细介绍

这是官网上专门针对使用asp.net的部署,很详细了

http://docs.cksource.com/CKEditor_3.x/Developers_Guide/ASP.NET/Integration_Beginners

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="web.test" %>
<%@ Register assembly="CKEditor.NET" namespace="CKEditor.NET" tagprefix="CKEditor" %>
<%@ Register src="Controllers/ClassList.ascx" tagname="ClassList" tagprefix="uc1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="./Scripts/scripts/jquery.1.3.2.js"></script>
    <script type="text/javascript" src="./Scripts/scripts/popup_layer.js"></script>

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


    </script>
    <style type="text/css">
        #form1
        {
            width: 852px;
        }
        #TextArea1
        {
            height: 162px;
            width: 436px;
        }
    </style>
</head>
<body style="width: 908px">
    <form id="form1" runat="server">
    <div>
      <div id="ele6" style="cursor:hand; color: blue; display:none;"></div>
    <div id="blk6" class="blk" style="display:none;">
        <div class="head"><div class="head-right"></div></div>
        <div class="main">                
            <a href="javascript:void(0)"  id="close6" class="closeBtn"></a>                
            <iframe src="upimg.aspx"></iframe>                    
        </div>            
    </div>
    <div style="width: 803px">
        <br />
          <CKEditor:CKEditorControl ID="CKEditor_memo" runat="server" Height="313px"  
            Width="747px"></CKEditor:CKEditorControl>
        <br />
    </div>
    </div>
   </form>
</body>
</html>

下面是上传页面设计

前台设计upimg.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="upimg.aspx.cs" Inherits="web.upimg" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <!--
    <script type="text/javascript" src="./Scripts/scripts/jquery.1.3.2.js"></script>
    <script type="text/javascript" src="./Scripts/scripts/popup_layer.js"></script>
    -->
    <style type="text/css">
        #form1
        {
            height: 112px;
            width: 297px;
        }
    </style>
</head>
<body style="height: 120px; width: 299px;" bgcolor="White">
    <form id="form1" runat="server" style="background-color: #CEFFCE">
     <div style="height: 116px; width: 299px">
         <br />
&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="upLoadFile" runat="server" />
         <br />
         <br />
         &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<asp:Button ID="Button1" runat="server" Text="上传" onclick="Button1_Click" />
        &nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="取消" />
        &nbsp;&nbsp;
        </div>
    </form>
</body>
</html>

后台操作代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.IO;
namespace web
{
    public partial class upimg : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }

       //点击上传按钮,如果文件路径不为空进行上传操作
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.upLoadFile.PostedFile.ContentLength != 0)
            {
                string imgdir = UpImg();

                //调用前台JS函数,将图片插入编辑器中即我们在addpic.js写的upimg函数
                string script = "window.parent.upimg('" + imgdir + "');"

                ResponseScript(script);
            }
            else
            {
                Response.Write("请选择图片");
            }
        }

      //点击取消按钮,关闭弹出窗口
        protected void Button2_Click(object sender, EventArgs e)
        {
            string script = "window.parent.close();";
            ResponseScript(script);
        }
        /// <summary>
        /// 输出脚本
        /// </summary>
        public void ResponseScript(string script)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("<script language='javascript' type='text/javascript'>");
            sb.Append(script);
            sb.Append("</script>");
            ClientScript.RegisterStartupScript(this.GetType(), RandomString(1), sb.ToString());
        }
        /// <summary>
        /// 获得随机数
        /// </summary>
        /// <param name="count">长度</param>
        /// <returns></returns>
        public static string RandomString(int count)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] data = new byte[count];
            rng.GetBytes(data);
            return BitConverter.ToString(data).Replace("-", "");
        }

      //上传函数我将图片都存在了服务器根目录下的./upfile/images文件夹下
        public string UpImg()
        {
            string imgdir ="";
            if (this.upLoadFile.PostedFile.ContentLength != 0)
            {
                string fileFullName = this.upLoadFile.PostedFile.FileName;//
                int i = fileFullName.LastIndexOf(".");
                string fileType = fileFullName.Substring(i);
                if (fileType != ".gif" && fileType != ".jpg" &&
                    fileType != ".bmp" && fileType != ".jpeg" &&
                    fileType != ".png")
                {
                    Response.Write("文件格式不正确");
                    Response.End();
                }
                else
                {
                    DateTime now = DateTime.Now;
                    string newFileName = now.Millisecond + '_' + upLoadFile.PostedFile.ContentLength.ToString() + fileType;
                    upLoadFile.PostedFile.SaveAs(Server.MapPath("/upfile/images/" + newFileName));
                    imgdir = "./upfile/images/" + newFileName;
                }
            }
            return imgdir;
            
        }
    }
}

感谢一下博文博主

http://www.cnblogs.com/lts8989/archive/2011/08/04/2127326.html

http://www.cnblogs.com/dg5461/articles/1746484.html

参考代码请到我的资源中下载


 

posted @ 2013-07-24 21:11  坚固66  阅读(362)  评论(0编辑  收藏  举报