標籤:
首先感謝前輩們的無私奉獻。貼出參考地址
http://zhidao.baidu.com/link?url=Q0ZM405OFNy_xAHSut9TepRJxgXCxFayQttrQz1N82dlA1_JnAb4Ojdl-b9T0AyzPNcgdHWI5h-66RUcVWLW6Mb295rWGUXJFyLw1GBrvwK
貼出
按照前輩的指示。我複製代碼存為了一個js檔案。引入。關於之前的js代碼請移步我貼出的連結。
最開始,我一字不改地複製了代碼,除了修改了檔案上傳的url。測試,發現總是報錯,並且不進入sucess也不進入failure。斷點檢查發現是因為伺服器返回的資料格式不對,在解析成json的時候,extjs內部出錯了。這裡貼出一下後台關鍵代碼僅供參考,後台我用的是asp.net:
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["type"] != null && Request.QueryString["type"] == "newsImage") { Response.Write(InsertNewsImage()); Response.End(); } } private string InsertNewsImage() { string uploadPath = "D:\test"; string downloadPath = "http://localhost/UploadFiles"; try { string path = uploadPath + "/NewsImage/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } HttpPostedFile file = Request.Files[0]; if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) { return "{success:false,error:‘上傳檔案為空白‘}"; } string extName = "." + file.FileName.Substring(file.FileName.LastIndexOf(‘.‘) + 1); string saveName = Guid.NewGuid().ToString() + extName; file.SaveAs(path + "\\" + saveName); return "{success:true,filepath:‘" + downloadPath + "/NewsImage/" + saveName + "‘}"; } catch (Exception e) { return "{success:false,error:‘" + e.Message + "‘}"; } }
注意,後台一定要返回json格式的數組,並且帶一個bool類型的success傳回值。其他的就可以根據自己的需要返回。
目前為止,可以上傳了,也可以顯示圖片了。但是美中不足的是,圖片如果上傳太大,顯示的太大太大了就,不好控制。於是我加了一個寬高限定上去。
然後這裡還有個問題,大家也都會發現。就是返回後的圖片總是在文本的最前面,也就是說,無法插入到之前游標在的地方,為什麼呢?
於是我仔細去看前輩的方法,也仔細去找extjs 的api看看有沒有記錄滑鼠游標的方法。最後,我看到前輩們用的這個方法
if (Ext.isIE) {
editor.insertAtCursor(element.outerHTML);
}
我去翻閱了一下insertAtCursor的方法,這個方法是這樣子的:
function(b){if(!this.activated){return}if(Ext.isIE){this.win.focus();var a=this.doc.selection.createRange();if(a){a.collapse(true);a.pasteHTML(b);this.syncValue();this.deferFocus()}}else{this.win.focus();this.execCmd("InsertHTML",b);this.deferFocus()}}
這裡大家其實可以發現原因了。在插入映像之前,代碼先獲得文字框的焦點,在焦點處建立一個Range,這裡可以理解成建立一個空元素吧,然後把後台返回的映像的html插入到這個元素裡面。注意一下,這裡擷取焦點這個方法focus()是在上傳圖片之後執行的,擷取焦點之後建立Range。問題就在這裡了。在上傳圖片的時候,文字框是失去焦點的,也就是說,那個時候並不知道游標在哪個地方,因為沒有焦點。所以最後總是把圖片插在文字的最前面。我們只需要把擷取焦點並建立Range的邏輯放在彈出上傳對話方塊之前就好了。然後再把返回的映像路徑放到Range裡面。下面貼出外掛程式全部代碼!
var HTMLEditor = Ext.extend(Ext.form.HtmlEditor, { addImage: function() { var editor = this; editor.win.focus(); var range = editor.doc.selection.createRange(); var imgform = new Ext.FormPanel({ region: ‘center‘, labelWidth: 55, frame: true, bodyStyle: ‘padding:5px 5px 0‘, autoScroll: true, border: false, fileUpload: true, items: [{ xtype: ‘textfield‘, fieldLabel: ‘選擇圖片‘, id: ‘UserFile‘, name: ‘UserFile‘, inputType: ‘file‘, allowBlank: false, blankText: ‘檔案不可為空‘, anchor: ‘90%‘ }, { xtype: ‘textfield‘, fieldLabel: ‘高(像素)‘, id: ‘height‘, name: ‘height‘, allowBlank: false, regex: /^\d+$/, regexText: ‘請輸入數字‘, blankText: ‘請填寫圖片顯示的高度‘, anchor: ‘90%‘ }, { xtype: ‘textfield‘, fieldLabel: ‘寬(像素)‘, id: ‘width‘, name: ‘width‘, allowBlank: false, regex: /^\d+$/, regexText: ‘請輸入數字‘, blankText: ‘請填寫圖片顯示的寬度‘, anchor: ‘90%‘}], buttons: [{ text: ‘上傳‘, handler: function() { if (!imgform.form.isValid()) { return; } var formValues = imgform.form.getValues(); var width = formValues["width"]; var height = formValues["height"]; if (!width || !height || width == "0" || height == "0") { MessageBox(‘錯誤‘, "請填寫正確的寬度和高度"); return; } imgform.form.submit({ waitMsg: ‘正在上傳......‘, url: ‘SaveAffix.aspx?type=newsImage‘, success: function(form, action) { var element = document.createElement("img"); element.style.width = width + "px"; element.style.height = width + "px"; element.src = action.result.filepath; if (Ext.isIE) { if (range) { range.collapse(true); range.pasteHTML(element.outerHTML); editor.syncValue(); editor.deferFocus() } } else { var selection = editor.win.getSelection(); if (!selection.isCollapsed) { selection.deleteFromDocument(); } selection.getRangeAt(0).insertNode(element); } form.reset(); win.close(); }, failure: function(form, action) { form.reset(); if (action.failureType == Ext.form.Action.SERVER_INVALID) MessageBox(‘上傳失敗‘, action.result.error); } }); } }, { text: ‘關閉‘, handler: function() { win.close(this); }}] }) var win = new Ext.Window({ title: "上傳圖片", width: 300, height: 200, modal: true, border: false, iconCls: "img.gif", layout: "fit", items: imgform }); win.show(); }, createToolbar: function(editor) { HTMLEditor.superclass.createToolbar.call(this, editor); this.tb.insertButton(16, { cls: "x-btn-icon", icon: "img.gif", handler: this.addImage, scope: this }); } });
使用方法:var Content = new HTMLEditor({ fieldLabel: ‘內容‘, width: 600, height: 250, value: contentValue });
最後值得一提的是,這隻是一個例子,我沒有判斷上傳檔案的類型。大家可以在前端判斷也可以在後端判斷返回錯誤提示。祝愉快。
Extjs 3.0 htmleditor實現插入圖片功能