KindEditor粘贴时候自动上传远程图片(非本地)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Joyhen/article/details/50588489

KindEditor版本:4.1.10 (2013-11-23),具体可以去官网下载:http://kindeditor.net/down.php

基本的配置这里不说了,官网有文档,贴代码:

<textarea id="content" style="width:80%;height:100px;"></textarea>

//定义编辑器对象
var editor;

//异步加载编辑器
$.getScript('../kindeditor/kindeditor-min.js', function () {
	KindEditor.basePath = '../kindeditor/';
	editor = KindEditor.create('textarea[id="content"]', {
			id : 'editor_id',
			uploadJson : '../kindeditor/asp.net/upload_json.ashx',
			fileManagerJson : '../kindeditor/asp.net/file_manager_json.ashx',
			allowFileManager : true, //默认false
			resizeType : 1,
			items : [
				'undo', 'redo', '|',
				'fontname', 'fontsize', '|',
				'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|',
				'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|',
				'image', 'link', '|', 'preview'],
			autoHeightMode : true, //默认值: false
			afterCreate : function () {
				this.loadPlugin('autoheight');

				var __doc = this.edit.doc;
				//KindEditor.ctrl(__doc, 'V', function () {
				//    alert('123');
				//});
				$(__doc).bind('paste', null, function () { //右键粘贴, 包括 ctrl+v
					setTimeout(function () {
						parent.uploadWebImg(editor);
					}, 200);
				});
			},
			afterChange : function () {
				$('.word_count').html(this.count()); //(字数统计包含HTML代码。)
			},
		});
});
这里注意,要修改下kindeditor-min.js这个文件中的一个地方,不然粘贴的文本在事件响应之后(表现就是没有内容粘贴到编辑器中)

通过源代码可以在这里看到:https://github.com/kindsoft/kindeditor/blob/master/kindeditor-all.js


影响的具体方法就看自己这么写了,我的uploadWebImg代码贴到下面,用的layer弹窗组件,具体看它的官网api,这里不多说。

//上传远程图片
function uploadWebImg(editor) {
    var relaceSrc = []; //图片地址对象容器
    var imgs = $(editor.html()).find('img');

    imgs.map(function () {
        var _src = $(this).attr('src');
        //if ((_src.indexOf('http://') >= 0 || _src.indexOf('https://') >= 0) && checkimgok(_src)) {
        if (_src.indexOf('http://') >= 0 || _src.indexOf('https://') >= 0) { //考虑可能有动态生成的图片
            relaceSrc.push({ k: _src });
        };
    });

    if (relaceSrc.length == 0) return;

    var msg = '内容包含' + relaceSrc.length.toString() + '张远程图片,是否现在上传?';

    confirmLayerNormal(msg, function (_index) {
        var loading = layer.load(0);
        var paramdata = {
            action: "791c252eee12530f4f3af326674b7d97",
            arg: { imgs: relaceSrc },
        };

        doAjaxPost(paramdata, function (result) {
            layer.close(loading);
            if (!result.success) {
                SuperSite.MsgError(result.msg);
                return;
            }

            //替换编辑器图片源
            var _content = editor.html();
            $(relaceSrc).each(function (idx, dom) {
                _content = _content.replace(dom.k, result.data[idx].value);
            });
            editor.html(_content);

            SuperSite.MsgOK('远程图片上传成功');
        });
        layer.close(_index);
    });
};

服务端的代码:

/// <summary>
/// 上传远程图片
/// </summary>
private void UploadWebImg()
{
	var ajaxdata = base.GetActionParamData<PArgUploadWebImg>();
	if (ajaxdata == null || ajaxdata.imgs == null || ajaxdata.imgs.Count == 0)
		Outmsg(false, outmsg: "未获取到上传的图片地址");

	var len = ajaxdata.imgs.Count;
	var tempurl = new List<KeyValueDesc>();
	var stkimg = new Stack<KeyValue>(len); //上传栈列

	for (int i = 0; i < len; i++)
	{
		var img = ajaxdata.imgs[i].k.Trim();

		if (stkimg.Any(x => x.value == img))  //刚刚上传过了(说明有重复的图片要上传)
		{
			var loadedpath = stkimg.First(x => x.value == img).value;
			tempurl.Add(new KeyValueDesc
			{
				key = i.ToString(),
				value = loadedpath,
				desc = (int)EnumCenter.UploadImgStatus.Repeat
			});
			continue;
		}

		var tb = DownLoadWebImg(img);
		stkimg.Push(new KeyValue { key = i.ToString(), value = tb.Item2 }); //推入栈
		tempurl.Add(new KeyValueDesc
		{
			key = i.ToString(),
			value = tb.Item2,
			desc = tb.Item1 ?
			(int)EnumCenter.UploadImgStatus.OK :
			(int)EnumCenter.UploadImgStatus.Error
		});
	}

	Outmsg(true, outdata: tempurl);
}
private Tuple<bool, string> DownLoadWebImg(string url)
{
	try
	{
		var dt = DateTime.Now;
		var folder = "/upload/image/" + dt.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
		var newfile = dt.ToString("HHmmss_ffff", DateTimeFormatInfo.InvariantInfo) 
					+ url.Substring(url.LastIndexOf('.')); //扩展名(带.号)
		var filepath = Server.MapPath(folder);

		if (!Directory.Exists(filepath))
		{
			Directory.CreateDirectory(filepath);
		}

		using (WebClient mywebclient = new WebClient())
		{
			mywebclient.DownloadFile(url, filepath + newfile);
			return new Tuple<bool, string>(true, folder + newfile);
		}
	}
	catch (Exception ex)
	{
		Tools.LogHelp.WriteLog("下载远程图片失败", ex);
		return new Tuple<bool, string>(false, url); //返回原图地址
	}
}


没有更多推荐了,返回首页