当前位置: 首页 > 技术分享  > 开发技术 > 网站运营

kindeditor 图片本地化

2015/5/6 17:06:18 人评论

在使用Kindeditor编辑网站内容时考虑这样一个场景:编辑人员往往会从其它页面将内容复制到Kindeditor编辑器中。如果所复制的内容中包含…


在使用Kindeditor编辑网站内容时考虑这样一个场景:编辑人员往往会从其它页面将内容复制到Kindeditor编辑器中。如果所复制的内容中包含图片,则需要首先将图片从源地址下载到本地,然后将其上传到本网站所在的服务器,否则图片仍然会指向你所复制的页面或者文档,后期图片链接异常将会导致图片在页面中无法正确打开。当编辑人员处理许多的文档的时候,这样的操作无疑非常繁琐。能否让Kindeditor自动识别粘贴到其中的内容,并将图片自动上传到服务器呢?下面的代码实现了这一功能。


有关如何在页面中使用Kindeditor可以去查看官方网站的文档,这里不再详细介绍。

实现该功能的基本思路:在Kindeditor编辑器的keyup事件中添加代码,以检查编辑器的内容中是否包含图片;找出需要自动上传到服务器的图片,通过Ajax方式调用图片上传程序将图片上传到服务器;在Ajax的回调函数中将对应图片的src地址修改为本地相对地址。

上图是最终实现效果。程序会自动识别编辑器中的内容,如果有图片需要上传,则会在编辑器的顶部显示一条提示信息。用户点击“上传”链接,程序会通过Ajax请求调用图片上传程序,并在回调函数中将对应图片的src地址修改为本地相对地址。

具体实现步骤及相关代码:

1. Kindeditor编辑器修改

找到kindeditor.js文件,在keyup()事件中添加自定义代码。不同版本的Kindeditor所提供的代码差别可能会比较大,需要借助于官方文档进行查找。本文基于Kindeditor 4.1.9版本。

2. auto.js文件代码


function df() {
    var haspicContainer = document.getElementById("has_pic");
    if (haspicContainer == null) {
        haspicContainer = document.createElement("div");
        haspicContainer.id = "has_pic";
        haspicContainer.innerHTML = "<input type='text' id='piclist' value='' style='display:none;'/><div id='upload'><b>您有图片需要上传到服务器</b>&nbsp;&nbsp;<a href='javascript:uploadpic();' >上传</a></div><div id='confirm'></div>";
        $(".ke-toolbar").after(haspicContainer);
    }

    var img = $(".ke-edit-iframe").contents().find("img");

    var piccount = 0;
    var sstr = "";
    $(img).each(function (i) {
        var that = $(this);
        if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {
            piccount++;
            if (i == $(img).length - 1)
                sstr += that.attr("src");
            else
                sstr += that.attr("src") + "|";
        }
    });

    $("#piclist").val(sstr);
    document.getElementById("has_pic").style.display = (piccount > 0) ? "block" : "none";
}

function closeupload() {
    $("#has_pic").hide();
    $("#upload").show();
}

function uploadpic() {
    var piclist = encodeURI($("#piclist").val());
    if (piclist.length == 0) return false;

    $.ajax({
        url: "../../editor/imgauto/uploadpic.ashx",
        data: "pic=" + piclist,
        type: "GET",
        beforeSend: function () {
            $("#upload").hide();
            $("#confirm").text("正在上传中...");
        },
        success: function (msg) {
            if (msg !== "") {
                var str = new Array();
                str = msg.split('|');
                var img = $(".ke-edit-iframe").contents().find("img");

                $(img).each(function (i) {
                    var that = $(this);
                    if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {
                        that.attr("src", "/upload/image/" + str[i]);
                        that.attr("data-ke-src", "/upload/image/" + str[i]);
                    }
                });

                $("#confirm").html(img.length + "张图片已经上传成功!&nbsp;&nbsp;<a href='javascript:closeupload();'>关闭</a>");
            }
            else $("#confirm").text("上传失败!");
        }
    });
}
其中的$(".ke-edit-iframe").contents().find("img")用来查找编辑器内容中的所有图片。默认情况下,编辑器的内容被存放在iframe元素中,该iframe拥有class="ke-edit-iframe"的属性。程序会判断每个图片src属性的值中是否包含"http://"或者"https://",从而确定该图片是远程图片还是本地图片。如果图片为远程图片,则通过jQuery的ajax方法调用uploadpic.ashx将图片上传到服务器。同时在回调函数中修改对应图片的src地址。



3. uploadpic.ashx文件代码


public class uploadpic : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string pic = context.Request.QueryString["pic"];

        string[] arr = pic.Split('|');
        string sstr = "";
        UpLoadIMG st = new UpLoadIMG();
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].IndexOf("http://") >= 0 || arr[i].IndexOf("https://") >= 0)
            {
                string std = st.SaveUrlPics(arr[i], "../../uploads/image/");
                if (std.Length > 0)
                {
                    if (i == arr.Length - 1)
                        sstr += std;
                    else
                        sstr += std + "|";
                }
            }
        }
        context.Response.Write(sstr);
    }

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

public class UpLoadIMG
{
    public string SaveUrlPics(string imgurlAry, string path)
    {
        string strHTML = "";
        string dirPath = HttpContext.Current.Server.MapPath(path);

        try
        {
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + imgurlAry.Substring(imgurlAry.LastIndexOf("."));

            WebClient wc = new WebClient();
            wc.DownloadFile(imgurlAry, dirPath + newFileName);
            strHTML = ymd + "/" + newFileName;
        }
        catch (Exception ex)
        {
            //return ex.Message;
        }
        return strHTML;
    }
}
远程图片通过WebClient方法下载到服务器的相对路径"/uploads/image/"中,并且会按照日期自动生成文件夹和对应的文件名。返回的结果中包含了以"|"分隔的所有图片的本地相对地址,在步骤2的auto.js文件的uploadpic()函数中,回调方法success获取到该值并进行解析,将地址赋值给对应图片的src属性。

原文出处:kindeditor/ckeditor编辑器加+图片自动上传成功。本文中的代码做了适当调整和优化。


相关技术

  • 律师函来了-请各大企业主咨询网站管理人员

    客户收到了“至DedeCMS用户的函”,合计金额7800元。这引起了我们的反思...企业主是不懂技术的,更不懂是否有法律风险,贪图便宜请外面的人员做的网站,没想到带来了风险。织梦CMS是开源免费网站系统,已经深入人心,只是随便自家网站发布公告,就采取诉讼手段,确实不太…

    2022/2/8 10:36:11
  • 查看异常端口应用,结束异常进程

    1、 Cmd输入命令:netstat -a -o 查询所有端口和对应PID信息查询对应端口号 netstat –ano|findstr “端口号” ,如netstat –ano|findstr “8080”记下PID,最后一行为PID,这里为396 2,Cmd输入命令:taskkill -f -pid PID号,如taskkill -f -pid 396。

    2015/7/13 15:15:34
  • 5个技巧有效提升网站流量

    网站需要创造价值,如果只是设计得漂亮或者使用华丽酷炫的技术是远远不够的。建站最重要的目的是为了给公司创造效益,如果吸引不到访客…

    2014/9/17 7:57:06
  • 按Ctrl缩放网页功能

    访问部分网站,发现字太小,看不清楚。想起了利用Ctrl+鼠标滚轮进行放大查看。关闭网页后,查看其他网页,字体确变的很大,影响美观。利…

    2014/9/16 12:38:04

共有条评论 网友评论

验证码: 看不清楚?