ExtJS 3.0 htmleditor Implement Insert Picture function

Source: Internet
Author: User

First of all, thank the predecessors for their selfless dedication. Post a reference address

Http://zhidao.baidu.com/link?url=Q0ZM405OFNy_xAHSut9TepRJxgXCxFayQttrQz1N82dlA1_ Jnab4ojdl-b9t0ayzpncgdhwi5h-66rucvwlw6mb295rwguxjfylw1gbrvwk

Paste out

Follow the instructions of the Elder. I copied the code to save it for a JS file. Introduced. For the previous JS code please click on the link I posted.

At first, I copied the code without a word, except to modify the URL of the file upload. Test, found always error, and do not enter the sucess also do not enter the failure. The breakpoint check was found because the data returned by the server is not in the correct format, and when parsing to JSON, ExtJS internal error. Here to post the background key code for reference only, backstage I use asp:

protected void Page_Load (object sender, EventArgs e) {if (request.querystring["type"]! = NULL &&amp ;                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: ' Upload file is empty '} '; } 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 + "'}";   }        }

Note that the background must return an array of JSON format with a success return value of type bool. Others can be returned according to their own needs.

So far, you can upload or display pictures. But the drawback is that the picture if the upload is too large, the display is too big too big, bad control. So I added a wide-height limit up.

And then there's a problem, and everyone will find it. The image that is returned is always at the front of the text, that is, cannot be inserted where the cursor was before, why?

So I carefully to see the method of the predecessor, also carefully to find ExtJS API to see if there is no way to record the mouse cursor. In the end, I saw the way the seniors used it.

if (Ext.isie) {
Editor.insertatcursor (element.outerhtml);
}

I went through the Insertatcursor method, which is this way:

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 ()}}

Here we can actually find out why. Before inserting an image, the code first gets the focus of the text box, creating a range at the focus, which can be understood as creating an empty element, and then inserting the HTML of the image returned from the background into the element. Note that this method of getting focus is performed after uploading the image, and the range is created after the focus is taken. Here's the problem. When uploading a picture, the text box loses focus, that is, it does not know where the cursor is at that time because there is no focus. So in the end always put the picture in the front of the text. All we need to do is put the logic that gets the focus and create range before the pop-up upload dialog box. Then put the returned image path inside the range. Post the plugin all code below!

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:t Rue, items: [{xtype: ' TextField ', Fieldlabel: ' Select Picture ', ID: ' Userfi Le ', name: ' UserFile ', inputtype: ' File ', Allowblank:false, b Lanktext: ' File cannot be empty ', Anchor: ' 90% '}, {xtype: ' TextField ', Fieldla                Bel: ' High (pixels) ', id: ' Height ', name: ' Height ', allowblank:false,            Regex:/^\d+$/, Regextext: ' Please enter the number ', Blanktext: ' Please fill in the height of the image display ', Anchor: ' 90% '                }, {xtype: ' TextField ', Fieldlabel: ' Wide (pixels) ', id: ' Width ',   Name: ' Width ',             Allowblank:false, regex:/^\d+$/, Regextext: ' Please enter Number ', Blanktext                    : ' Please fill in the width of the image display ', Anchor: ' 90% '}], buttons: [{text: ' Upload ',                        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 (' error ', "Please fill in the correct width and height");                        Return                            } imgform.form.submit ({waitmsg: ' uploading ... '),                                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.deletefrom                                    Document ();                                } selection.getrangeat (0). Insertnode (Element);                                } form.reset ();                            Win.close ();                                }, Failure:function (form, action) {form.reset (); if (Action.failuretype = = Ext.form.Action.SERVER_INVALID) MessageBox                            (' Upload failed ', action.result.error);                    }                        }); }}, {text: ' Off ', handler:function () {WIN.C Lose (This); }}]}) var win = new Ext.window ({title: "Upload Picture", width                    : 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 (+, {cls: "X-btn-icon", Icon: "Img.gif",            Handler:this.addImage, scope:this}); }        });

How to use: var content = new HTMLEditor ({fieldlabel: ' content ', width:600, height:250, value:contentvalue});

Finally, it's worth mentioning that this is just an example of the type of upload file I didn't judge. You can judge on the front end and return the error message at the back end. I wish you a happy.

ExtJS 3.0 htmleditor Implement Insert Picture function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.