Welcome 微信登录

首页 / 脚本样式 / JavaScript / js控件Kindeditor实现图片自动上传功能

Kindeditor是一款功能强大的开源在线HTML编辑器,支持所见即所得的编辑效果。它使用JavaScript编写,可以无缝地与多个不同的语言环境进行集成,如.NET、PHP、ASP、Java等。官方网站可以查看这里:http://kindeditor.net/index.php

Kindeditor本身提供了许多非常实用的插件,由于代码开源,开发人员可以根据需要对其进行任意扩展和修改。

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

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

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

该功能不支持将Word中的图片复制出来并上传到服务器。 



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

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

1. Kindeditor编辑器修改 

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



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>  <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"); elsesstr += 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: "asp.net/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", "/uploads/image/" + str[i]);that.attr("data-ke-src", "/uploads/image/" + str[i]); }});$("#confirm").html(img.length + "张图片已经上传成功!  <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; elsesstr += 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属性。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。