xhEditor在線編輯器使用實例

使用xhEditor的最大好處就是不用去處理煩人的HTML標籤問題,研究了一天,記錄備用

前臺HTML:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Editor.aspx.cs" Inherits="xhEditor在線編輯器.Editor" %>

<!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 src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="Scripts/xhEditor/xheditor-1.2.1.min.js" type="text/javascript"></script>
    <script src="Scripts/xhEditor/xheditor_lang/zh-cn.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            //初始化編輯器
            $('#elem1').xheditor({ tools: 'full', width: '99.4%', height: '426px', forcePtag: false,
                upBtnText: '上傳', upMultiple: 1, upLinkUrl: 'upload.aspx',
                upImgUrl: 'upload.aspx', upImgExt: 'jpg,jpeg,gif,png',
                upFlashUrl: 'upload.aspx', upFlashExt: 'swf',
                upMediaUrl: 'upload.aspx', upMediaExt: 'wmv,avi,wma,mp3,mid'
            });
        });
        //存值
        function setValue() {
            $.ajax({
                cache: false,
                url: "upload.ashx",
                data: { "text": $("#elem1").val() },
                success: function (e) {
                    //alert("success");
                    window.location.href = "Success.aspx";
                }
            });
        }
        //取值
        function getText() {
            $.ajax({
                cache: false,
                url: "getValue.ashx",
                success: function (e) {
                    //alert(e);
                    $("#getDIV").append(e);
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" method="POST">
    <div id="editorDIV" style="width: 900px">
        <hr />
        <br />
        <textarea id="elem1" name="content" >test</textarea>
        <br />
        <hr />
        <input type="button" value="提交" οnclick="setValue()" />
        <input type="reset" name="reset" value="重置" />
        <input type="button" οnclick="getText()" value="取值"/>
    </div>
    <hr/>
    <div id = "getDIV">
        
    </div>
    </form>
</body>
</html>
<%--使用指南http://xheditor.com/manual/1--%>

處理後臺頁:

<%@ Page Language="C#" AutoEventWireup="true" CodePage="65001" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Web.UI.WebControls.WebParts" %>
<%@ Import namespace="System.Data.SqlClient" %>
<script runat="server">
    /*
 * upload demo for c# .net 2.0
 * 
 * @requires xhEditor
 * @author Jediwolf<[email protected]>
 * @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
 * 
 * @Version: 0.1.4 (build 111027)
 * 
 * 注1:本程序僅爲演示用,請您務必根據自己需求進行相應修改,或者重開發
 * 注2:本程序將HTML5上傳與普通POST上傳轉換爲byte類型統一處理
 * 
 */

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Charset = "UTF-8";

        // 初始化一大堆變量
        string inputname = "filedata";//表單文件域name
        string attachdir = "upload";     // 上傳文件保存路徑,結尾不要帶/
        int dirtype = 1;                 // 1:按天存入目錄 2:按月存入目錄 3:按擴展名存目錄  建議使用按天存
        int maxattachsize = 2097152;     // 最大上傳大小,默認是2M
        string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid";    // 上傳擴展名
        int msgtype = 2;                 //返回上傳參數的格式:1,只返回url,2,返回參數數組
        string immediate = Request.QueryString["immediate"];//立即上傳模式,僅爲演示用
        byte[] file;                     // 統一轉換爲byte數組處理
        string localname = "";
        string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

        string err = "";
        string msg = "''";

        if (disposition != null)
        {
            // HTML5上傳
            file = Request.BinaryRead(Request.TotalBytes);
            localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 讀取原始文件名
        }
        else
        {
            HttpFileCollection filecollection = Request.Files;
            HttpPostedFile postedfile = filecollection.Get(inputname);

            // 讀取原始文件名
            localname = postedfile.FileName;
            // 初始化byte長度.
            file = new Byte[postedfile.ContentLength];

            // 轉換爲byte類型
            System.IO.Stream stream = postedfile.InputStream;
            stream.Read(file, 0, postedfile.ContentLength);
            stream.Close();

            filecollection = null;
        }

        if (file.Length == 0) err = "無數據提交";
        else
        {
            if (file.Length > maxattachsize) err = "文件大小超過" + maxattachsize + "字節";
            else
            {
                string attach_dir, attach_subdir, filename, extension, target;

                // 取上載文件後綴名
                extension = GetFileExt(localname);

                if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上傳文件擴展名必需爲:" + upext;
                else
                {
                    switch (dirtype)
                    {
                        case 2:
                            attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                            break;
                        case 3:
                            attach_subdir = "ext_" + extension;
                            break;
                        default:
                            attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                            break;
                    }
                    attach_dir = attachdir + "/" + attach_subdir + "/";

                    // 生成隨機文件名
                    Random random = new Random(DateTime.Now.Millisecond);
                    filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

                    target = attach_dir + filename;
                    //記錄文件名和文件路徑
                    Session["filename"] = filename;
                    Session["route"] = target;
                    try
                    {
                        CreateFolder(Server.MapPath(attach_dir));

                        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                        fs.Write(file, 0, file.Length);
                        fs.Flush();
                        fs.Close();
                    }
                    catch (Exception ex)
                    {
                        err = ex.Message.ToString();
                    }

                    // 立即模式判斷
                    if (immediate == "1") target = "!" + target;
                    target = jsonString(target);
                    if (msgtype == 1) msg = "'" + target + "'";
                    else msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
                }
            }
        }

        file = null;

        Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
    }


    string jsonString(string str)
    {
        str = str.Replace("\\", "\\\\");
        str = str.Replace("/", "\\/");
        str = str.Replace("'", "\\'");
        return str;
    }


    string GetFileExt(string FullPath)
    {
        if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
        else return "";
    }

    void CreateFolder(string FolderPath)
    {
        if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
    }
    
</script>

保存到數據庫:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Data;

namespace xhEditor在線編輯器
{
    /// <summary>
    /// Summary description for getValue
    /// </summary>
    public class getValue : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string connStr = "server = .;database = Test1;uid=sa;pwd=password";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string id = Guid.NewGuid().ToString();
                string sqlstr = "select top 1 text from dbo.editor";
                using (SqlCommand cmd = new SqlCommand(sqlstr, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter dapter = new SqlDataAdapter(cmd))
                    {
                        DataTable ds = new DataTable();
                        dapter.Fill(ds);
                        context.Response.Write(ds.Rows[0][0].ToString());
                    }
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

從數據庫讀取數據:

using System;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Data;
namespace xhEditor在線編輯器
{
    public partial class Success : System.Web.UI.Page
    {
        protected string text = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            string connStr = "server = .;database = Test1;uid=sa;pwd=password";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string id = Guid.NewGuid().ToString();
                string sqlstr = "select top 1 text from dbo.editor";
                using (SqlCommand cmd = new SqlCommand(sqlstr, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter dapter = new SqlDataAdapter(cmd))
                    {
                        DataTable ds = new DataTable();
                        dapter.Fill(ds);
                        text = ds.Rows[0][0].ToString();
                    }
                }
            }
        }
    }
}

層次結構:


數據庫結構:


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