前些天發(fā)現(xiàn)一些群友對(duì)于KindEditor編輯器上傳圖片有一些疑問(wèn),不知道后臺(tái)怎么處理上傳的圖片以及如何添加水印,

這里只對(duì)上傳單張圖片及添加水印做一下基礎(chǔ)講解(大神請(qǐng)快速路過(guò)),上傳附件以及多張圖片的使用方式大同小異,請(qǐng)根據(jù)案例自行研究。


下面對(duì)KindEditor在Asp.net里的使用方法做一個(gè)詳細(xì)的說(shuō)明,文章結(jié)尾會(huì)有附件DEMO下載,

如有不理解請(qǐng)直接下載附件查看,這里只做簡(jiǎn)單詳解拋磚引玉,如果你有更好的方法可以忽略本篇講解。


第一步:頁(yè)面加載KindEditor編輯器

<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="Form1" runat="server">
    文章內(nèi)容:<textarea onmouseover="this.focus();" id="content" class="form-control" rows="25"
        style="max-height: 2222px; max-width: 95%;" placeholder="請(qǐng)上傳圖片試試看" runat="server"></textarea>
    </form>
    <script src="/kindeditor-4.1.7/kindeditor-all-min.js" type="text/javascript"></script>
    <script type="text/javascript">
        KindEditor.ready(function (K) {
            K.create('#content', {
                resizeType: 1,
                allowPreviewEmoticons: false,
                allowImageUpload: true,
                allowMediaUpload: false,
                allowFlashUpload: false,
                autoHeightMode: true,
                uploadJson: '/Interface/PubInterface.ashx?act=pubinterimg', //上傳圖片接口
                afterCreate: function () {
                    this.loadPlugin('autoheight');
                },
                items: ['source', '|', 'undo', 'redo', '|', 'preview', 'print', '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', 'flash', 'media', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink']
            });
        });
    </script>
</body>
</html>

第二步:配置上傳圖片接口



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace KindEditorUploadImg.Interface
{
    /// <summary>
    /// kindeditor上傳圖片案例
    /// 作者:hnxxbl.cn
    /// </summary>
    public class PubInterface : IHttpHandler
    {
        delegate void func(HttpContext context);
        static Dictionary<string, func> services = new Dictionary<string, func>();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string urlstr = string.Empty;
            string act = context.Request["act"];
            try
            {
                services[act](context);
            }
            catch
            {
                context.Response.Write("{\"error\":1,\"url\":\"\",\"message\":\"請(qǐng)求異常\"}");
                return;
            }
        }
        static PubInterface()
        {
            #region kindeditor上傳圖片案例
            services.Add("pubinterimg", delegate(HttpContext context)
            {
                HttpPostedFile postedFile = context.Request.Files["imgFile"];//接收?qǐng)D片對(duì)象
                try
                {
                    string fileExt = GetFileExt(postedFile.FileName); //文件擴(kuò)展名,不含“.”
                    int fileSize = postedFile.ContentLength; //獲得文件大小,以字節(jié)為單位
                    string newFileName = DateTime.Now.Ticks   "."   fileExt; //隨機(jī)生成新的文件名
                    string upLoadPath = "/UploadEditorImg/"   DateTime.Now.ToString("yyyyMMdd")   "/"; //上傳目錄相對(duì)路徑
                    string fullUpLoadPath = context.Server.MapPath(upLoadPath); //上傳根目錄
                    string newFilePath = upLoadPath   newFileName;
                    //檢查文件擴(kuò)展名是否合法
                    if (fileExt != "png" && fileExt != "jpg" && fileExt != "gif" && fileExt != "jpeg")
                    {
                        context.Response.Write("{\"error\":1,\"url\":\"\",\"message\":\"只允許上傳png/jpg/jpeg/gif格式文件\"}");
                        return;
                    }
                    if (fileSize > 5 * 1024 * 1024)
                    {
                        context.Response.Write("{\"error\":1,\"url\":\"\",\"message\":\"上傳圖片過(guò)大,單張圖片請(qǐng)勿超過(guò)5兆\"}");
                        return;
                    }
                    //檢查上傳的物理路徑是否存在,不存在則創(chuàng)建
                    if (!Directory.Exists(fullUpLoadPath))
                    {
                        Directory.CreateDirectory(fullUpLoadPath);
                    }

                    #region 添加水印
                    byte[] byteData = FileHelper.ConvertStreamToByteBuffer(postedFile.InputStream);
                    byteData = ImgWater.AddImageSignText(byteData, fileExt, "hnxxbl.cn", 9, 90, "宋體", 35);
                    //保存文件
                    FileHelper.SaveFile(byteData, fullUpLoadPath   newFileName);
                    #endregion
                    //處理完畢,返回JOSN格式的文件信息
                    string UrlStr = "http://"   context.Request.Url.Authority;//拼接當(dāng)前端口路徑
                    context.Response.Write("{\"error\":0,\"url\":\""   UrlStr   newFilePath   "\",\"message\":\"上傳成功,保存后生效\"}");
                    return;
                }
                catch
                {
                    context.Response.Write("{\"error\":1,\"url\":\"\",\"message\":\"上傳過(guò)程中發(fā)生意外錯(cuò)誤\"}");
                    return;
                }
            });
            #endregion


        }

        /// <summary>
        /// 返回文件擴(kuò)展名,不含“.”
        /// </summary>
        /// <param name="_filepath">文件全名稱</param>
        /// <returns>string</returns>
        public static string GetFileExt(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return "";
            }
            if (_filepath.LastIndexOf(".") > 0)
            {
                return _filepath.Substring(_filepath.LastIndexOf(".")   1); //文件擴(kuò)展名,不含“.”
            }
            return "";
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
第三步:前面兩步已經(jīng)把主要代碼寫出來(lái)了,請(qǐng)自行研究,下面來(lái)看下頁(yè)面演示



第四步:請(qǐng)下載DEMO源碼自行研究,請(qǐng)注意:源碼中用到FileHelper.cs和ImgWater.cs兩個(gè)Helper幫助類。


點(diǎn)擊下載“Asp.net實(shí)現(xiàn)KindEditor編輯器上傳單張圖片添加水印”源碼DEMO 


注意:KindEditor官方對(duì)于在Asp.net、Java、PHP、ASP等語(yǔ)言中的具體用法給出了詳細(xì)的講解,點(diǎn)擊下載官方源碼DEMO


原文鏈接:Asp.net實(shí)現(xiàn)KindEditor編輯器上傳單張圖片添加水印