An Image Upload Extension for YUI Rich Text Editor

Before you begin: Read the updates at the bottom of the page. This post was written for an older version of the YUI library.

I've had nothing but good things to say about the Yahoo User Interface tools. It seems to me like the developers continually add all the things from other libraries that I like into one simple to use, well documented, overall good quality library.

The new addition of the rich text editor has left me no less pleased. I can now ditch the other editors I've used in the past in favor of one that will be maintained. (I've tried two that worked, but were becoming out-dated and didn't really have support.)

Yahoo's RTE has a great dialog for modifying images. You can't use it to upload images from your computer however. So far, every situation I've needed an RTE has called for the ability to add images from the users hard drive. I've created an extension that modifies the RTE image dialog to include a new input for browsing to an image. It uses the Yahoo Connection manager to upload the image in the background to your server, and then displays the image in the RTE after the file is successfully uploaded.

Here is how to use it:

  1. Place the required source code dependencies for YUI Editor and YUI Connection Manager in your html.
    <!-- Skin CSS file -->
    <link rel="stylesheet" type="text/css" href="">
    <!-- Utility Dependencies -->
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <!-- Needed for Menus, Buttons and Overlays used in the Toolbar -->
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <!-- Source file for Rich Text Editor-->
    <script src=""></script>
    <!-- Source for Connection Manager (Required for yuiImageUploader) -->
    <script src=""></script>
  2. Download the yuiImageUploader Source and add it to your included javascript dependencies
    <script src="/yui-image-uploader.js"></script>
  3. Instantiate your editor the same as you normally do. Then modify it with the yuiImageUploader function. The parameters for the function are the editor instance, the url to upload the file to, and the parameter name that the file will be uploaded with.
    var myEditor=new YAHOO.widget.Editor('rte_div',cfg);
    yuiImgUploader(myEditor, '/upload_url','param_name');
  4. Implement your upload handler on your server. I'm assuming if you're looking for this functionality, you already know how to do this. The important thing is the response. The content of the response is a JSON object. You must return a response with the Content-Type header set to 'text/html' however, because IE will attempt to open the response in a new window if the Content-Type header is something other than 'text/html'. Your object needs to have a status and an image_url variable. For a successful response, just return:
    For a failure, modify the status variable to be an error message that can be shown to the user:
    {status:'The image was too big.'}
  5. When your users click on the image button on the RTE editor, the yuiImageUploader modifies the image dialog to have an additional file field for uploading an image:

    YUI RTE Image Uploader

    The upload is done in the background with the Connect object provided by Yahoo's Connection Manager. If everything works ok, the URL returned by the server is placed in the image url input and the image is shown in the editor.

That's it. You can download the file here.

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.


I've created another post that shows a working example here.

I've added another example, this time with the server side script being implemented in PHP.

Update 10/31/08:
Thanks to bkinsey for providing updates to the client script for use with YUI 2.6. You can see his comment below or I've added downloadable file here.

Update 11/6/08:
I corrected errors in the script and added a working YUI 2.6 Image Uploader example.

Update 02/16/09:
Vijay Oruganty has provided a Java upload handler for the YUI image uploader.

Update 07/01/09:
I've added a working example with the 2.6 uploader and YUI 2.7. YUI 2.7 Image Uploader

Update 06/16/10:
Working example with YUI 2.8.1 added. Tagged the uploader git repository tag_v2.8.1. YUI 2.8.1 Image Uploader

135 Responses to “An Image Upload Extension for YUI Rich Text Editor”

  1. Tobi R.

    Hello Dennis,

    nice Extension, thank you very much!

    One little thing: Your tutorial says that the function name is “yuiImageUploader”, but in your downloadable script the name is “yuiImgUploader”.

  2. Dennis

    Thanks for the catch! Fixed.

  3. Paul

    Can you post an example of your code? I am having difficulty in adding the yuiImgUploader(); to the RTE.

  4. Dennis

    Unfortunately, this server doesn’t have the ability to upload images :( If you give details on what you’re having trouble with though, I may be able to help resolve the issue or update the article with more information.

  5. Paul

    Basically, this is the code I have so far:

    var myEditor = new YAHOO.widget.Editor(‘msgpost’, {
    height: ‘300px’,
    width: ‘700px’});
    yuiImgUploader(myEditor, ‘/upload_url’,’param_name’);

    When I add the yuiImgUploader function, the browse option does not come up. I have downloaded the .js file and put it in the proper place but it is still not displaying.

    Thanks for the help.

  6. Dennis

    In my usage, I put the yuiImgUploader call before the render call. Does that resolve the issue?

  7. Paul

    I tried that first, but this causes the whole RTE to fail, and I am left with just a textarea.

  8. Dennis

    Interesting, I just tried it either way and it worked find. Perhaps an error is being generated. Do you have a logging pane available to see if there is something failing underneath the hood?

  9. Paul

    I have Firebug, but it is not reporting any Javascript errors. I placed an alert to display the various errors in your catch statements, and came back with “ReferenceError: $ is not defined”. This was for “ee”.

  10. Dennis

    Woops, bug in the script.
    That should be Dom.get instead of $
    I’ve fixed the upload. The $ function is a dependency on another JS Library that I’ve been converting from.

  11. Paul

    That was it! Thanks for the help :-)

  12. Todd H.

    How about a demo?

  13. Dennis

    Dav Glass is working on integrating a demo into the YUI examples section for the editor. I’d provide one here, but I don’t have the ability to upload images to this server.

  14. mike

    Wow, I was planning on writing something similar this weekend… Thanks!

    It looks like you have a bug in your response handling code. I think this:

    if (o.status=’UPLOADED’) {

    should probably be:

    if (o.status == ‘UPLOADED’) {

  15. Tobi R.

    Hello Dennis,

    my IE6 trys to open a new document unless I leave the Response Content-Type simply away.

    At Nicholas C. Zakas says:

    “There’s no need to set the “Content-type” header for POST requests. The Connection Manager handles this for you behind the scenes.”

  16. Tobi R.

    Sorry, I think I have to correct a mistake in my last post. Nicholas C. Zakes talks about the Request- not the Response Header.

  17. Dennis

    Good Catch Mike! Fixed.

  18. Dennis

    Tobi, I’ll play around with this more in IE and edit the document accordingly today. I stuck that in because I had the same problem a while back where IE was trying to open the document in a new window. I may have remembered incorrectly how I fixed it.

  19. Dennis

    Tobi, You’re correct. I had it backwards in my tutorial. You have to set the content type to text/html Even Though the response is JSON. I think it would be fairly straight forward to pass in a function for a success handler as one of the parameters. That way you could return whatever you want from the server, and then simply have your success handler return the new image url. There is no specific reason to have the server return a response in JSON format other than it is convenient to parse.

  20. Tobi R.

    Hi Dennis,

    I substituted the toolbar addListener from “buttonClick” to “insertimageClick” to show the image uploader also in “edit mode”, not just in “insert mode”. Perhaps someone is interested in:

    function yuiImgUploader(rte, upload_url, upload_image_name) {
    YAHOO.log(“Adding Click Listener” ,’debug’);
    rte.addListener(‘toolbarLoaded’, function() {
    rte.toolbar.addListener(‘insertimageClick’, function() {
    var imgPanel = new YAHOO.util.Element(‘yui-editor-panel’);
    /* … */

  21. Dennis

    Thanks Tobi,
    Good suggestion. I’ve uploaded a new file that contains all the changes suggested so far.

  22. XerraX

    how do I implement the upload handler? (noob) i am trying to get the image upload in the yui component for Drupal CMS.

  23. Dennis

    You can check out the example I posted:

    My example however, is with TurboGears. The concepts are the same for most frameworks I’d think though.

  24. XerraX

    Well thanks for your answere, but thats too hard for a noob ^^

    if you are conform with Drupal you may can check out the issue here:


    that would be really nice :-) if not its ok too, greetings from europe

  25. XerraX


  26. Dennis

    I don’t have experience with Drupal. I’m sure I could create a plugin for it to handle the uploads, but I just don’t have the time to look at it right now with my other projects. Unfortunately, the best I can do at present is refer you to the Turbogears example I posted

  27. hiromi

    >yuiImgUploader(myEditor, ‘/upload_url’,’param_name’);

    I dont know what ‘param_name’ is gonna be…
    Could somebody tell me what it is?

    Thank you.

  28. Dennis

    It is the name of the parameter that your server expects to receive the image with. You might name it “image” or “file” or “picture”. It really doesn’t matter. Whatever you name it, the file will be posted to your server url with that parameter name. You can look at the working upload example if you want more details.

  29. XerraX

    Is it possible to do this without python? Only with SQL and PHP?
    *bothering you until you watch the links above and solve the problem ^^*

    Greetz from Europe, XerraX

  30. Dennis

    Any server side language should do. You just need to accept the file, store it somewhere, and return the URL for the image that the Editor can display.

  31. colin

    Has anyone ever encountered problems with this script on IE7? On the upload handler it tells me that r.responseText is undefined.

    Excellent script by the way!

  32. Dennis

    You may be having a server error. You can try my working example with IE and see if that works for you. (Linked at the end of the article.)

    I’ve found FireBug with FireFox is really nice for seeing what the request/response actually contain if that helps.

  33. colin

    I didn’t see the working example before, so thanks for pointing it out. Downloading that example and playing with some values helped me figure out the issue.

    For .NET devs out there, I had to modify the image handler I had written to add a context.Response.Flush() followed by context.Response.End() to get this working. My full test handler code is here (I just spit back Google’s logo instead of handling the image for testing purposes):

    context.Response.ContentType = “text/html”;

    Thanks again for this script. I intend on adding to a (free) open source project that I started very recently (YUI.NET); crediting this website for the image uploading piece. Anyone is free to check it out and use it, just know that it is extremely limited at this time and is not truly ready for public consumption yet:

    Thanks again

  34. alex

    Greetings everyone.
    I’m a total programming newbie, however i’ve managed to get this awesome extension working…well, almost. I’m building a CMS using PHP & MySQL, and i perfectly know how to upload images from a normal form with a PHP script that gets the image file from the $_FILES[‘param_name’] global variable, but this doesn’t seems to work in this case. Please, if anyone could tell me how should i write my PHP image upload handler i’ll be very grateful. Thanks in advance.

  35. Joe

    This is pretty great. If anyone is looking for a companion php upload script, I used Easy PHP Upload without too much trouble. It’s not my script so I can guarantee it or anything, but find it here:

  36. Cyle Carlson

    Joe, or anyone else, do you think you could post instructions for setting this up via PHP. For the life of me I can’t get it to work. Thanks!

  37. Dennis

    I’ve got it on my slate to post a PHP working example. I won’t be able to get to it for another couple weeks though. If in the mean time, anyone has an example already working, you’re more than welcome to post it.

  38. alex

    I’ve done it, this is my working php script. (GD must be enabled to do it this way)

    Thanks Dennis, this extension you made works great, it should be included on the default YUI Library.
    Geetings form Guadalajara, Mex.

  39. alex

    //defining a function to open theimage (only jpg/gif/png)
    function openImage ($file) {
    # JPEG:
    $im = @imagecreatefromjpeg($file);
    if ($im !== false) { return $im; }
    # GIF:
    $im = @imagecreatefromgif($file);
    if ($im !== false) { return $im; }
    # PNG:
    $im = @imagecreatefrompng($file);
    if ($im !== false) { return $im; }
    return false;
    //if file has been sent successfully:
    if (isset($_FILES[‘image’][‘tmp_name’])) {
    // open the file
    $img = $_FILES[‘image’][‘tmp_name’];
    $image = openImage($img);
    //if image can’t be opened, either its not a valid format or even an image:
    if ($image === false) {
    header(“content-type: text/javascript”);
    echo “{status:’this is not a valid format’}”;
    //the following is an optional image resizer.
    // get original size:
    $width = imagesx($image);
    $height = imagesy($image);
    // define new size (fixed width in pixels, proportional height:
    $new_width =450;
    $new_height = $height * ($new_width/$width);
    // create a blank jpg image with the new sizes:
    $image_resampled = imagecreatetruecolor($new_width, $new_height);
    // copy the original image into the new one
    imagecopyresampled($image_resampled, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    // create a new random numeric name to avoid rewriting other images already on the server…
    $ran = rand ();
    $ran2 = $ran.”.”;
    // define the uploading dir
    $path = “storing/path”;
    // join path and name
    $path = $path . $ran2.’jpg’;
    // copy the image to the server, alert on fail
    if(!imagejpeg($image_resampled,$path, 100)) {
    header(“content-type: text/javascript”);
    echo “{status:’error copying the image on server’}”;
    } else {
    //image wasn’t even sent:
    header(“content-type: text/javascript”);
    echo “{status:’no file was sent!’}”;
    //everything alright…
    header(“content-type: text/javascript”);
    echo “{status:’UPLOADED’, image_url:’$path’}”;

  40. alex

    well obviously i can’t post code here hehe
    you can see it here:

  41. Dennis

    Thanks Alex! You can post code here, it just needed moderated 1st.

  42. Tremor

    I tryed to use your exapmle ( on my hosting. It doesn`t work, though server supports uploading files.
    Can you help me, please?

  43. Dennis

    Hi Tremor, using Firebug on FireFox, I watched the Net window show what was happening. It appears you’ve uploaded the script to a different directory. The script tried to post to /yuieditor/upload_image and it received a 404 status from the server.

  44. Tremor

    Thank you :)
    And where i should put this folders?

  45. Dennis

    It doesn’t matter. You just need to pass the location where you’ve uploaded it to the yuiImgUploader function. Look at the 2nd parameter of the function and make sure that is correct.

  46. Tremor

    Thanks a lot.
    But now i have a new problem.
    Can you advice me, if u don’t tired to help me? :)

  47. Dennis

    Perhaps you should email me directly.

  48. Cyle Carlson

    Alex, thanks for the PHP upload script. However, this is all new to me. I understand how to direct a form to a PHP script for processing… but this method via AJAX is blowing my small mind. How do I get it so that when the upload link is pressed -> the PHP script is processed -> the file is uploaded –> file information is returned and displayed in the editor?

    Where should I place the function you supplied so that it can be executed? And would the yuiImgUploader call be written like this: (file used because of $file in the script)

    yuiImgUploader(myEditor, ‘/upload_url’,’file);

    I apologize for the newb questions… but I have tried everything I can think of to get this to work and am running a little dry. Thanks in advance.

  49. Cyle Carlson

    I’ve figured out many of my questions posted above — however I am stuck now at place where I find that when I click “Upload” — no POST information is transfered. My test page is here: Anyone have any ideas? I am using the PHP script posted my Alex. Thanks!

  50. Dennis

    Hi Cyle,

    I just tested your page. Your upload parameter to the yuiImgUploader function is set to “/upload_image”. There is no trailing slash. When I posted an image, I 1st got a redirect (301) to “/upload_image/” and then the request was made. I believe this is why your script doesn’t work. Just stick the trailing slash into your parameter so the POST isn’t redirected and then you won’t loose the posted image.


  51. Cyle Carlson

    Dennis, thanks for the help. You’re right. That did get rid of the (301)… however things still aren’t working.

    According to Firebug, there is no POST information begin sent — unless I am reading Firebug wrong. Any suggestions or insight? The PHP script is ending right off the bat because it doesn’t have any POST information to use.


  52. Dennis

    I used WireShare to confirm that the file is indeed being sent.

    Here is a snippet:

    Content-Disposition: form-data; name=”image”; filename=”ME.jpg”
    Content-Type: image/jpeg

    ……JFIF…..H.H…..C……………………………………….!………”$” .$…….C……………………………………………………………..?. 6..”………………………………..

    Are you looking for the “image” parameter in your server side script?

  53. Dennis

    I think your upload directory is not writable by the web server.

  54. Cyle Carlson

    You can take a look at my exact file/directory structure as well as the files I am using via this archive:

    And thank you so much for your help. I really appreciate it!

  55. Cyle Carlson

    Both upload_image and uploads have their permissions set at 777.

  56. alex

    Hi Cyle. I was working on my second website using this great extension with the php script i posted above, when i’ve encountered some troubles similar to yours, with no apparent reason…then i’ve found that the server i was UNIX based, wich is case-sensitive when reading headres, and it also needed a semi-colon at the end of the line…maybe yours is this kind too, so i sugest you to change all the headers on the php script from
    – header(

  57. RelaX


    I’ve got a very simple question.
    How do I point to an upload script (index.php).

    yuiImgUploader(oEditor, ‘/scripts/yui/build/yuieditor/index.php’,’img’);

    it doesn’t load the upload script at all. Or is it the wrong line?

    Please help.

  58. Dennis

    Is your “index.php” file the one that can accept the file for upload? Is the path correct? the 2nd parameter of the yuiImgUploader should be the relative path to a server side function that can accept the file (under the name given by the 3rd parameter).

  59. RelaX

    yes, I tried the file that was uploaded by one of the people from here:

    the image dir and uploadscript dir are set to “777”. (linux server).

    and this is the function that I use to call the upload script.

    (function() {
    var oEditor = new YAHOO.widget.Editor(‘editor’,
    height: ‘300px’,
    width: ‘500px’,
    handleSubmit: true
    yuiImgUploader(oEditor, ‘/~layouts/modules/scripts/yui/build/yuieditor/index.php’,’img’);

    above is the relative path to the uploadscript. Everything is fully loaded, and I can browse to the image. After pressing “upload image”, it does nothing.

  60. Dennis

    I’m actually playing around with it right now. I don’t know if there script has a bug or if there is something I’m missing. I’ll post back when I’ve figured it out. Do let me know if you find the answer sooner. I suggest turning up the error logging for php and starting there.

  61. Dennis

    After debugging a little, I found the the imagecreatefromjpeg function was dying. I’m not sure why. Perhaps someone else could expound on this.

    I cut everything out everything but the actual upload code and simply saved the file that was uploaded and it worked. I’ll be completing a working example in PHP sometime today I think.

  62. RelaX

    That’d be great! Thanks for helping me with this. I’m sure that many people will find this very useful.

  63. Dennis
  64. RelaX

    Hey again,

    (i try to post this message, didn’t work the first time)

    Everything loads up perfectly, but after pushing “upload image”, it doesn’t do anything.

    – I do the following…

    so it’s pointed to:

    yuiImgUploader(myEditor, ‘/scripts/yui_img_uploader.php’,’image’);

    (permissions set to 777):

    full path on server:

    $path = “uploads/”;

    $path = “/” . $path;

    this doesn’t work. I’m using php4 on linux. I tried all kinds of combinations to point to the uploadscript.

  65. alex

    Hi Dennis, hey i think you forgot to moderate my las post, theres some php code about headers that could Cyle. About the imagecreatefromjpeg function, as i said before, it belongs to the php GD library as well as all the other image manipulation functions i used on that script, and it must be compiled and enabled on your server php config. Maybe that’s why it was dying while you was trying it. However, the php script on your example does the work fine.

  66. Dennis

    Well, I found one comment, the one before the one you just made, that was erroneously marked as spam, but I didn’t see another waiting moderation or marked as spam.

    Thanks for the input though. The image processing is a little beyond the scope of what I wanted to handle here, but it is probably pertinent for anyone who wants to actually process an image on the server side with PHP. Nice work.

  67. Lars

    To get this working in Safari I needed to set the encoding of the enclosing form to “multipart/form-data”. Below this line:
    var img_elem=Dom.get(‘insertimage_url’);

    I added:
    Dom.getAncestorByTagName(img_elem, ‘form’).encoding = ‘multipart/form-data’;

  68. Dennis

    @Lars: I thought it was probably something to do with the form encoding but hadn’t had a chance to work on it. Thank you for posting back the solution. I’ve updated the script with your solution.

    If you’ve previously downloaded the script, you ought to do so again to get the latest version with this fix.

  69. Rami

    Hey, I am beginner with JavaScripts..I need to take the innet html from the C# file .. how can i do that????What I know is that it is client server side..

  70. Dennis

    You’re correct that you need additional server programming. On the PHP RichText example, someone posted some server code in Perhaps that will help you.

  71. abhishek198

    Hi Dennis,
    I was trying to use the RTE ..
    but when i click on the upload image button… nothing actually happens far as i see it .. the link points to the same page .. instead of some other page to upload the image ..

    this is what i have edited :
    yuiImgUploader(myEditor, ‘/img_uploader.php’,’image’);


  72. abhishek198

    Hi Daniel,
    In the function yuiImgUploader(a,b,c) …
    the second parameter as per the example specified above is the path of the directory where the image will be uploaded ..
    but if you see the comments .. it says path of the uploader script .. which one of these is correct ..
    and is there any constraint on the name of the uploader script…


  73. Dennis

    It’s the path of the uploader script. The uploader script can be whatever you wish. I’ll edit the page to reflect that correctly. Also, if you post the link to your example that isn’t working, we can probably find out why.


  74. maxg

    Has anyone gotten this to work with a ColdFusion based upload handler? Even with the revised script setting the encoding variable of the posted form, CF still returns the The cffile action=”upload” requires forms to use enctype=”multipart/form-data” error. Anyone had this problem?

  75. Jeoffrey

    I’ve a display problem.
    In Mozilla it works just fine but in IE the created textbox ‘insertimage_upload’ has an width from 0px.Everything works fine, including the upload, only I can ‘t see the selected path+file.

  76. Dennis

    You’ll have to tweak the style sheet appropriately for IE.

  77. bkinsey

    In case anyone is interested, I updated the js code for yui 2.6.0

      rte: The YAHOO.widget.Editor instance
      upload_url: the url to post the file to
      upload_image_name: the name of the post parameter to send the file as
     Your server must handle the posted image.  You must return a JSON object
     with the result url that the image can be viewed at on your server.  If 
     the upload fails, you can return an error message.  For successful
     uploads, the status must be set to UPLOADED.  All other status messages,
     or the lack of a status message is interpreted as an error.  IE will 
     try to open a new document window when the response is returned if your
     content-type header on your response is not set to 'text/javascript'
     Example Success:
     {status:'UPLOADED', image_url:'/somedirectory/filename'}
     Example Failure:
     {status:'We only allow JPEG Images.'}
    function yuiImgUploader(rte, editor_name, upload_url, upload_image_name) {
        // customize the editor img button 
        YAHOO.log( "Adding Click Listener" ,'debug');
        rte.addListener('toolbarLoaded',function() {
            rte.toolbar.addListener ( 'insertimageClick', function(o) {
                try {
                    var imgPanel=new YAHOO.util.Element(editor_name + '-panel');
                    imgPanel.on ( 'contentReady', function() {
                        try {
                            var Dom=YAHOO.util.Dom;
                            if (! $(editor_name + '_insertimage_upload'))
                                var label=document.createElement('label');
                                var img_elem=Dom.get(editor_name + '_insertimage_url');
                                Dom.getAncestorByTagName(img_elem, 'form').encoding = 'multipart/form-data';
                                YAHOO.util.Event.on ( editor_name + '_insertimage_upload', 'change', function(ev) {
                                    YAHOO.util.Event.stopEvent(ev); // no default click action
                                    YAHOO.util.Connect.setForm ( img_elem.form, true, true );
                                    var c=YAHOO.util.Connect.asyncRequest(
                                    'POST', upload_url, {
                                            try {
                                                // strip pre tags if they got added somehow
                                                resp=r.responseText.replace( //i, '').replace ( //i, '');
                                                var o=eval('('+resp+')');
                                                if (o.status=='UPLOADED') {
                                                    Dom.get(editor_name + '_insertimage_upload').value='';
                                                    Dom.get(editor_name + '_insertimage_url').value=o.image_url;
                                                    // tell the image panel the url changed
                                                    // hack instead of fireEvent('blur')
                                                    // which for some reason isn't working
                                                    Dom.get(editor_name + 'insertimage_url').focus();
                                                    Dom.get(editor_name + 'insertimage_upload').focus();
                                                } else {
                                                    alert ( "Upload Failed: "+o.status );
                                            } catch ( eee ) {
                                                YAHOO.log( eee.message, 'error' )
                                    return false;
                        } catch ( ee ) { YAHOO.log( ee.message, 'error' ) }
                } catch ( e ) {
                    YAHOO.log( e.message, 'error' )
  78. Dennis

    Thanks! I added a link to the article with the downloadable script you provided.

  79. glowfish

    I can’t get the editor load correctly with the updated code for yui 2.6. Keep getting “Object expected” error in IE. BTW, I’m not very familiar with javascript.

    I have this line in html:
    yuiImgUploader(myEditor, ‘/upload.php’,’image’);

    …but the updated 2.6 code needs 4 parameters?

    function yuiImgUploader(rte, editor_name, upload_url, upload_image_name) {

    What should I put as parameter for “editor_name”?
    I tried “yui-editor” after comparing old code with 2.6 one, but still get the same error.

    If I remove the yuiImgUploader function completely from the page, then the editor loads correctly, so everything else is set up right.

    Any suggestions?

  80. Dennis

    I haven’t had a chance to check it out. I’ll try and post a working example here in the next few days. Let us know in the mean time if you find any errors or a way to fix your problem.

  81. Rob

    Yep… I think bkinsey there might have posted the wrong copy of his code there – because there’re a couple of things that just won’t work.

    I’ve updated it to add a few little things – and I have it working fine with 2.6 now:

    (By the way, the ‘editor_name’ parameter is just the id of the rte element. So you want to be doing something like this when you’re setting up your editor:

    myEditor = new YAHOO.widget.Editor('myEditorElmId', myConfig);
    yuiImgUploader(myEditor, 'myEditorElmId', '/upload_url', 'param_name');
    function yuiImgUploader(rte, editor_name, upload_url, upload_image_name) {
       rte.addListener('toolbarLoaded',function() {
           rte.toolbar.addListener ( 'insertimageClick', function(o) {
               try {
                   var imgPanel = new YAHOO.util.Element(editor_name + '-panel');
                   imgPanel.on ( 'contentReady', function() {
                       try {
                           var Dom=YAHOO.util.Dom;
                           //if (! $(editor_name + '_insertimage_upload')) {
                           if (get(editor_name + '_insertimage_upload') == null) {
                               var label=document.createElement('label');
                               var img_elem=Dom.get(editor_name + '_insertimage_url');
                               Dom.getAncestorByTagName(img_elem, 'form').encoding = 'multipart/form-data';
                               YAHOO.util.Event.on ( editor_name + '_insertimage_upload', 'change', function(ev) {
    							   Dom.get(editor_name + '_insertimage_url').value=Dom.get(editor_name + '_insertimage_upload').value;
    							   var uploadStatus = Dom.get(editor_name+'_upload_status'); 
    							   uploadStatus.innerHTML= ' Uploading...';
                                   YAHOO.util.Event.stopEvent(ev); // no default click action
                                   YAHOO.util.Connect.setForm ( img_elem.form, true, true );
                                   var c=YAHOO.util.Connect.asyncRequest(
    	                               'POST', upload_url, {
    	                                       try {
    	                                           // strip pre tags if they got added somehow
    	                                           //var resp=r.responseText.replace( //i, '').replace ( //i, '');
    	                                           var resp=r.responseText.replace( '//i', '').replace ( '//i', '');
    	                                           var o=eval('('+resp+')');
    	                                           if (o.status=='UPLOADED') {
    	                                               Dom.get(editor_name + '_insertimage_upload').value='';
    	                                               Dom.get(editor_name + '_insertimage_url').value=o.image_url;
    	                                               // tell the image panel the url changed
    	                                               // hack instead of fireEvent('blur')
    	                                               // which for some reason isn't working
    	                                               Dom.get(editor_name + 'insertimage_url').focus();
    	                                               Dom.get(editor_name + 'insertimage_upload').focus();
    												   uploadStatus.innerHTML= '';
    	                                           } else {
    	                                               uploadStatus.innerHTML= '';
    	                                       } catch ( eee ) {
    	                                           YAHOO.log( eee.message, 'error' )
    	                                           uploadStatus.innerHTML= '';
                                   return false;
                       } catch ( ee ) { YAHOO.log( ee.message, 'error' ) }
               } catch ( e ) {
                   YAHOO.log( e.message, 'error' )
  82. Rob

    Oh, hello… It’s the commenting utility on this site – it’s stripping out the code below here:


  83. Dennis

    Rob, I edited your comment to add pre tags around your code.

    You can do this:

    <pre lang=”javascript”>
    // formatted js code
    function sample() {}
    < /pre>

  84. Dennis

    Unfortunately, it seems wordpress is stripping those tags out. I may need to edit something to allow them to be posted. I modified my comment manually.

  85. msanders

    A working copy of bkinsey’s 2.6 code with the missing HTML tags can be found by doing a Google search for ‘yuiImgUploader’ and selecting the top hit, which is a post by bkinsey to the ydn-javascript Yahoo Group. (I attempted to post the link here, but the comment system seems to think it’s spam!)

    You’ll need to remove the word wrapping in an editor. I also found that I didn’t have ‘$’ defined and so needed to change the line:

    if (! $(editor_name + ‘_insertimage_upload’))


    if (! YAHOO.util.Dom.get(editor_name + ‘_insertimage_upload’))

    Hope this helps…

  86. Rob

    msanders is right – and the missing code there is just the same as the previous version – though the upload happens when the file input is changed, rather clicking a link.

    You know what.. A video embedding control would be nice too.. I’ll post one when I get it done.

  87. Dennis

    I’ve corrected the script bugs and added a working example with YUI 2.6 here.

  88. phoebebright

    Using this great function with django. This worked for me.

    In say where to put pics


    In YUIImageUploader put call to django url:
    yuiImgUploader(myEditor, params[‘divName’], ‘/json/uploadimage/’,’image’);

    And tell how to handle it:


    Then create the view to handle the upload:

    def uploadimage(request):	 
    		#		upload_full_path = os.path.join(settings.MEDIA_ROOT, upload_dir)
    		upload_full_path = settings.CONTENT_IMAGES
    		upload = request.FILES['image']
    		dest = open(os.path.join(upload_full_path,, 'wb+')
    		for chunk in upload.chunks():
    		result='{status:"UPLOADED",image_url:"%s%s"}' % (settings.CONTENT_IMAGES_URL,
    		return HttpResponse(result,mimetype='content-type: text/html')
    	except Exception, e:
    		return HttpResponse("Error in uploading image")
  89. phoebebright

    Note that indents have been left out above – indent one below try and except!

  90. Dennis

    Thanks for the additional info. I added pre tags around your code so at least the indents work. The pre tags work a lot better in posts than they do in comments but it ought to help at least.. especially for python.

  91. phoebebright

    Thanks Dennis!

  92. phoebebright

    Am having problems with my implementation on PCs. I assume it is the Content Type. Originally I had text/html and works on mac and firefox on PC but not IE. Then tried text/javascript as suggested in a post elsewhere but still doesn’t work on IE. The example on this site works fine using IE so wondered what is going on. An example of the django code I used is posted above and wondered if anyone could spot a problem and whether this could be a django problem?

  93. Dennis

    I think the text/javascript content type might be a mistake. I recall having problems like this for IE and I think the correct is text/html to not get a popup asking you to save the response. You can use Firebug in Firefox to see the response headers. Test the example here as well as yours and see what the difference is.

  94. phoebebright

    This doesn’t work in firefox mac
    return HttpResponse(result,mimetype=’Content-Type:text/html’)
    But this does (but not in IE)
    return HttpResponse(result,mimetype=’content-type: text/html’)

    PIcky or what!

  95. Vijay Oruganty

    Hi Dennis
    Thanks for the post and putting together a working example. I wrote the upload handler in Java (a simple servlet as needed in one of our apps) and combined it with rest of your stuff. Let me know I can upload the eclipse project as a zip.


  96. Dennis

    You can send it to me, and I’ll attach it to the post, or if you like, just post a link to it here in the comments.

  97. Rosh D

    Just wanted to know if this works even if you are using YUI’s SIMPLE editor. Currently, for adding images, it shows a Script Prompt asking for Link URL.. I want to implement this browse functionality in it. I tried this, but the script prompt is still the same.

    var myEditor = new YAHOO.widget.SimpleEditor(‘editor’, {
    height: ‘300px’,
    width: ‘600px’

  98. Dave


    I’ve got it working with CodeIgniter (PHP framework), except for one thing: the image doesn’t show up within the editor. (The image does get uploaded, the URL is coming back fine and does get inserted into the Editor content, but the image doesn’t display within the Editor).

    BTW, this is Editor v2.7.

    Any ideas? thanks.

  99. Dennis

    Can you see the image in your browser at the same URL that is being passed back to the editor? You can use firebug in FireFox to inspect the element and see any errors too.

  100. Dave

    Yes, the image does show up, so the upload succeeded, the URL is good. If I provide a URL in the img dialog directly, rather than doing an upload, then I do see the image in the Editor, so its not an underlying problem with Editor.

    The difference appears to be that images provided with a direct URL have a class=”yui-img” within the img tag, but uploaded images do not. I suspect that if I could get class=”yui-img” into the img tag then things would start working as expected.

  101. Dennis

    Perhaps yui-image-uploader needs updated again to work with 2.7.

  102. Dave


    Ok, I found the problem i was having: I was passing back a relative URL, and Editor was doing a GET relative to my current CodeIgniter pretty URL, rather than relative to my site URL. So it was doing at GET for:
    but the image was at

    In this case what I was returning was “uploads/1234.jpg”.

    The confusing thing was that the img tag that got inserted into the text actually worked – I would see the image when I pulled the text out of the database and displayed it because the src was “uploads/1234.jpg” and is found by the browser. But I couldn’t see the image inside Editor at all.

    So now, I return a full URL ( and all is well.

    BTW, class=”yui-img” started showing up in img tags once Editor could find the image.

    Thanks for your excellent addition to YUI Editor!

  103. measaura

    Hi all,

    I’ve been using the uploader script 2.6 with YUI 2.7 RTE without any problem. Just add the uploader js and initiate the image uploader.

    Most of the problems are due to folder / permission issues. Please make sure that your rte / uploader form location and the uploaded image folder are sync with each other. If it’s in a different folder, make sure you have the correct path for the folders from your uploader & also server side PHP file.

  104. Rajasekhar


    i am using 2.6 image uploader.when i select image automatically image is uploaded to my folder .and target is inserted to iframe.i am using this in google opensocial in ning container.My problem is i am unable to get the response .but my image is uploaded to folder.

    in connection.js file

    in asyncRequest function

    // responseText and responseXML will be populated with the same data from the iframe.
    // Since the HTTP headers cannot be read from the iframe

    obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
    obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

    in below catch block i am getting alert like “Permission denied to get property Window.document”

    can any one tell me what causes this error.

    this is very urgent for me.

    please help me out


  105. Dennis

    Have you debugged this problem with Firebug in Firefox? Also, you might try enabling the YUI logger and adding additional logging statements. Looks like a browser issue to me.

  106. Rajasekhar

    how can i enable the yui logging .this is very urgent for me.can u give me the solution.

  107. Dennis

    Probably the best thing is to join the YUI forums and give more context for your problem. Also, the YUI site has a page that shows everything you need to know about logging.

  108. Peter

    Anyone using YUI 2.6.0 should be aware of this lovely little bug :

    In Firefox (3 for sure, maybe 2) : If you select a previously inserted image and click the “Insert Image” button it will remove the existing image from the editor and bring up the “Insert new image” dialog rather than the “Edit existing image” dialog.

    It was fixed but you have to update to 2.7.0 and hope that nothing else breaks.

    Thank you for your examples Dennis, they have proved very helpful.

  109. cajchris

    Hi there,

    I am using this image upload extension and have it almost complete, however I noticed that when I select the image from my file browser the URL does not appear in the Image URL box and the image does not appear in the editor.

    I was adding alerts throughout the code and it seems that it cannot find the FORM element that is the parent of the “Upload” label that is added. Where is the HTML for this FORM created as when it executes the line:

    Dom.getAncestorByTagName(img_elem, ‘form’).encoding = ‘multipart/form-data’;

    it seems to find some other FORM on my page that is completely unrelated to this pop up image browser.


  110. Dennis

    @Peter. I just added the 2.7 example. So far, I haven’t found anything else that breaks.

  111. Dennis

    @Chris: You ever fix this?

  112. ibrahim m gitau

    thanks alot for the recipee,,,,,,,,,,kenya

  113. Matt Richards

    Hi there.

    I wonder if you could shed some light on an issue I’m experiencing.

    I’ve written & implemented an extension to integrate the YUI RTE & Image Upload extension into ExpressionEngine 1.6.7 everything seems to work other than the actual upload. After selecting an image from the file browser I get the following JS error:

    this._formNode.submit is not a function

    If I take everthing out of the EE environment it works, so I’m assuming I have some kind of conflict. As far as I know there are no other JS libraries loaded. As I have almost no experience with the YUI I was wondering if you might be able to point me in the right direction, I appreciate that the issue probably lies within EE but I don’t even have a clue how I might work around it.


  114. Dennis

    Firefox w/ Firebug installed is your friend. Make sure the framework is including all the correct YUI headers. Do you have additional HTML on the page that may be conflicting? Enable the YUI logging console too.

  115. Andy Vaughan

    == Image uploads failing in IE7 ==

    Just solved this after banging my head against it for a while (ahh, the joys of web development!).

    If the “name” attribute of the form that contains the used by the YUI Rich Text Area is set to “action” then the image upload script fails in IE7.

    For some reason it makes an ajax call to the page containing the form rather than the server-side script designed to handle the image upload. Changing the “name” attribute to something else (such as “save”) resolves the issue.

    Hope this helps someone else in the unlikely event that they have the same problem.


  116. An Example Rich Text Editor Image Upload with PHP | All My Brain

    […] Tags: ajax, image upload, javascript, php, rich text editor, rte, yui After my previous image uploader and turbogears image uploader posts, the overwhelmingly most requested information has been a PHP […]

  117. Image Upload with YUI Editor 2.5.0 | All My Brain

    […] YIU Rich Text Editor Image Upload Extension. […]

  118. Candice Witz

    I’m looking for a multi-OEM product offering but within a single catalog and preferably through a single web portal – are there any consulting services that offer that? In researching I found this but not sure if there are bigger consulting firms that can offer this kind of thing?

  119. abhishek198

    Does the RTE work with YUI version 2.8.0r4 ?

  120. YUI Image Uploader Example with TurboGears | All My Brain

    […] image upload, javascript, python, rich text editor, rte, turbogears, yui After completing the YUI Image Uploader, I received a lot of requests for a working example. I didn't originally create a working example, […]

  121. YUI Image Uploader for Rich Text Editor 2.8.0r4- Emin KURA

    […] this manually and then copy its link to URL input. This way is cumbersome, i have googled and found this post which presents a plugin that stands for image uploader for YUI rich text editor. This plugin adds […]

  122. YUI Image Uploader works with YUI 2.8.1 | All My Brain

    […] double check that the image upload still works fine with YUI 2.8.1 If you haven't read the original YUI Image Uploader page, start there. After that, you can use this page for an example getting the script to work with […]

  123. Brilver

    I tried the codes, image is uploaded, but when submit the form only the texts added to the data base.. Please help Urgent..

  124. Shreyo

    is there any specific reason, why the pop-up is not working? when i click the upload button on the yui upload button, the default images comes, but not the pop-up for further process..
    any of your solution will be helpful..

  125. Madhan

    can any one tel. how to get the values from the editor and have to post the values in my database.hep me

  126. Dennis

    There are several examples of how to do that in multiple different server side languages if you search the YUI examples on this site.

  127. madhan

    hi i am working on image upload
    still my code is not working i dunno were is the mistake
    can anyone send me the source code.

  128. madhan

    yuiImgUploader(myEditor, ‘/wp-content/uploads/2007/12/yui_img_uploader.php’,’image’);explain this line

  129. Juan

    Hello. This script is beautiful and works perfectly with my backend perl scripts. I have one little problem though. When I upload an image into the RTE followed imediatley by some text ‘foo’ I’m able to retrieve the image and text value through jQuery with no problem. But if I were to reverse it like start off with some text ‘foo’ immediately followed by an uploaded image I’m only able to retrieve the text but not the image value. Any idea as to why? Thnx!

  130. Dennis

    madhan: You need to read the other posts on this blog about backend programming. The line you are having is part of what ties the front end to a back end script.

    Juan: You’d probably get your answer better on the YUI forums. I always accessed the content with the YUI api directly.

  131. Igor

    madhan: I guess I had same troubles today.
    There should be 4 args in function in last version of this plugin:

    var myEditor=new YAHOO.widget.Editor(‘rte_div’,cfg);
    yuiImgUploader(myEditor, ‘editor_name’, ‘/upload_url’,’param_name’);

    More info I found here:

  132. Igor

    Whoops, sorry – little mistake. Second arg of yuiImgUploader() should be same with first arg of Editor constructor:

    var myEditor=new YAHOO.widget.Editor(‘rte_div’,cfg);
    yuiImgUploader(myEditor, ‘rte_div’, ‘/upload_url’,’param_name’);

  133. Nic

    Hello, I was wondering if there is an easy way to strip out some of the options from the image uploader dialogue? I’ve dug around but I can’t seem to locate the piece that you add the “upload” button to.


  134. hope

    Thanks for the script, but
    please whee do add this status message?
    {status:’UPLOADED’, image_url:’/somedirectory/filename’}

  135. Dennis

    That message is returned by your script on your server to indicate the upload worked correctly. On the client side you don’t have to do anything. The image appears in the editor.