KindEditor貼上時候自動上傳遠端圖片(非本地)
阿新 • • 發佈:2019-01-02
基本的配置這裡不說了,官網有文件,貼程式碼:
<textarea id="content" style="width:80%;height:100px;"></textarea>
這裡注意,要修改下kindeditor-min.js這個檔案中的一個地方,不然貼上的文字在事件響應之後(表現就是沒有內容貼上到編輯器中)//定義編輯器物件 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程式碼。) }, }); });
影響的具體方法就看自己這麼寫了,我的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); //返回原圖地址 } }