Example YUI Image upload with YUI 2.6.0

I wanted to add an example of the yuiImgUploader script working with YUI version 2.6.0. 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 the latest YUI.

That changes from the previous 2.5 Image uploader are quite small. If you were using a pre 2.6 version of the editor, simply change the location of a couple scripts and add your editor name to the yuiImgUploader function parameters.

Here is the new yui-image-uploader26.js file.


Here is the initialization JavaScript for the editor on this page. You can find information on Yahoo’s Rich text editor here.


  
  
 
 
 



I left the server side image upload script the same as with previous versions of this script.

Feel free to leave a comment or contact me if you have questions or suggestions.

This entry was posted in Programming and tagged , , , , , . Bookmark the permalink.

39 Responses to Example YUI Image upload with YUI 2.6.0

  1. mygenesis says:

    Great ap, thx :o)
    I’ve been writing a new application of MyGenesis CMS using the YUI rich text, your upload mod is perfect. Works great, however, one thing I noticed with the upload php script, it uploads images under the server name which causes permission errors. To fix this just add a chmod to it like so

    $hout=fopen($path,”w”);
    $chmod = chmod($path, 0766); //set the appropriate permissions.
    fwrite($hout,$image);
    fclose($hout);

    on another subject, I’m trying to figure out how to change the style within the textarea, can’t find any documentation on it though, any ideas?

    thx,
    Karen

  2. mygenesis says:

    Me again >.< I’ve searched for days to implement custom css in the iframe, finally found a post by Dave Glass so I implemented it with your image upload, just in case anyone else is looking for something similar, here’s the code

    (function() {
    var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;

    var myConfig = {
    height: ‘300px’,
    width: ‘522px’,
    handleSubmit: true,
    dompath: true,
    animate: true
    };

    var myEditor = new YAHOO.widget.Editor(‘msgpost’, myConfig);
    myEditor.on(‘editorContentLoaded’, function() {
    var head = this._getDoc().getElementsByTagName(‘head’)[0];
    var link = this._getDoc().createElement(‘link’);
    link.setAttribute(‘rel’, ‘stylesheet’);
    link.setAttribute(‘type’, ‘text/css’);
    link.setAttribute(‘href’, ‘editor.css’);
    head.appendChild(link);

    var link2 = this._getDoc().createElement(‘link’);
    link2.setAttribute(‘rel’, ‘stylesheet’);
    link2.setAttribute(‘type’, ‘text/css’);
    link2.setAttribute(‘href’, ‘editor.css’);
    head.appendChild(link2);
    }, myEditor, true);
    yuiImgUploader(myEditor, ‘msgpost’, ‘img2.php’,’image’);
    myEditor.render();

    dp.SyntaxHighlighter.HighlightAll(‘code’);
    })();

    of course change the editor.css file to your css file location.

    Best Regards,
    Karen

  3. Aneesh says:

    Hi Mr. Dennis,

    I have a problem with my code. The image upload script (yui-img-uploader.php) is not initiating when i select the pic to upoad.

    Please help me out here…

    This is my code:

    var myEditor = new YAHOO.widget.Editor(‘text234’, {
    height: ‘300px’,
    width: ‘522px’,
    handlesubmit: true,
    dompath: true, //Turns on the bar at the bottom
    animate: true //Animates the opening, closing and moving of Editor windows
    });
    yuiImgUploader(myEditor, ‘text234’, ‘/app/webroot/yui-image-uploader.php’,’image’);
    myEditor.render();
    //Inside an event handler after the Editor is rendered
    YAHOO.util.Event.on(‘submit’, ‘click’, function() {
    //Put the HTML back into the text area
    myEditor.saveHTML();

    //The var html will now have the contents of the textarea
    var html = myEditor.get(‘element’).value;
    });

    *Note: I’m using this on cakePHP.

  4. Dennis says:

    Have you installed FireBug (for FireFox) and enabled YAHOO logging? Most people find the problem pretty fast after watching for the appropriate log messages.

  5. Duncan Brown says:

    @Aneesh Just guessing but you shouldn’t need /app/webroot/ because cakephp will direct it to there anyway.

  6. Pingback: Vine » Blog Archive » [YUI] Uploader + Rich Text Editor

  7. aristanoble says:

    Hey Dennis, I LOVE the upgrade you’ve made to this app as i knew there was something a bit missing to the original. I have a question though, how would it be possible to marry both techniques thereby allowing the user to insert a local image or, if on a restricted public computer, they can then insert a remote image?

  8. aristanoble says:

    LOL, I totally overlooked that this technique I’ve spoken of is already in place! I’ve just been RE-impressed! Way to go Dennis!

  9. ebaretta says:

    i still can not get the image to post or upload and all i did was copy paste and change the editor_name to the name of my editor, chmod my dir and directed to the dir in the php file(which i have basically the same code doing it in another app i made for the site)… everything else is the basic coding used throughout..

  10. ebaretta says:

    i’m using the rte_img_uploader26.js and the php file from above

  11. Dennis says:

    I suggest installing FireBug and watching your request/response to see exactly what the problem is. Also, enable yahoo logging so you can see any error messages/exceptions.

  12. sky says:

    for some reason mine fails here:

    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 );

    which is loacted in the img uploader js, after adding a image, i get no response, no alert, no nothing

  13. Dennis says:

    Install FireBug and see what is happening. See my previous comment too.

  14. phoebebright says:

    Am having a nightmare getting this working with any browser other than Firefox/Mac. Safari is uploading the file but is then return the response as a download. I got it to write out the Response Accept variable and this is gzip, deflate.
    This is probably a red herring, but just in case, is that what you would expect??

    I suspect django is putting something into the request that is messing things up, but I am not a python expert and I have had no repsonse to my posts on the django user group.

    Anyone with any ideas on what I could try, please let me know. I have racked up about 3 solid days on this issue (which includes trying other RTE editors) all to no avail…

  15. phoebebright says:

    Here is the full request header from firebug:

    Host

    mpv.ie

    User-Agent

    Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.6) Gecko/2009011912 Firefox/3.0.6

    Accept

    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

    Accept-Language

    en-us,en;q=0.5

    Accept-Encoding

    gzip,deflate

    Accept-Charset

    ISO-8859-1,utf-8;q=0.7,*;q=0.7

    Keep-Alive

    300

    Connection

    keep-alive

    Referer

    http://mpv.ie/admin/carpoint/page/vauxhall1/

    Cookie

    sessionid=6fe759c37519e0214221b9a57d18dbb3

  16. Dennis says:

    Do other browsers work with my example here?

    Have you learned how to enable the YAHOO logging messages and view them in any browser? The library has enough debug and error messages that you should be able to see exactly what is going on in pretty much any browser. Adding and viewing the logging panel is an exercise left up to you though. There are a lot of examples on the YUI developer site for the logger component.

    You can always add additional debug messages if you need too.

  17. phoebebright says:

    Yes, your example works which is why I’m blaming Django! Will explore messaging tomorrow. Thanks for the quick response.

  18. zaphod says:

    So what happens if someone removes or deletes the image from the text? Does it remain on the server as an orphan?

  19. Dennis says:

    You’re correct. I dealt with orphans by looking at the contents of the text area when saving and any images not references were flagged for deletion. You could go further and implement a listener that fires when the image is deleted and then handle the event appropriately. Sounds like a good add-on to this project actually.

  20. zaphod says:

    I think the listener idea is a good one. The server side I can handle with PHP, but I am new to YUI and Ajax. I was looking into using YUI to re-do the back-end admin pages of my software and I like the look and feel of YUI.

    I also noticed that the editor in WordPress allows for drag-and-drop image uploading into the edit box. How hard would that be to implement in YUI?

  21. Dennis says:

    Shouldn’t be too hard. I’ve been a little out of the loop lately on YUI stuff since I’ve been working on embedded software lately. The trend for the editor was to have more and more listener’s that you could attach handlers too though. I’d wager everything is already in place for you to implement a delete image handler.

  22. phil says:

    Hi dennis,
    this is my error message
    “\nWarning: fopen(/image/12278.jpg) [function.fopen]: failed to open stream: No such file or directory in C:\wamp\www\YUI\image\upload.php on line 23\n\nWarning: fwrite(): supplied argument is not a valid stream resource in C:\wamp\www\YUI\image\upload.php on line 24\n\nWarning: fclose(): supplied argument is not a valid stream resource in C:\wamp\www\YUI\image\upload.php on line 25\n{status:’UPLOADED’, image_url:’/image/12278.jpg’}”

    I can’t see the image and there is nothing uploaded in the /image directory.

    thanks

  23. Dennis says:

    Are you trying to use the sample PHP script from this site? That script is quite Unix centric. You’ll need to adapt it for a Windows based server.

  24. phil says:

    yes, I’m using your sample php and the site work vwith WAMP. I’ll try this on a Linux server.
    Thanks

  25. phil says:

    it work’s fine with a LAMP, thank’s
    phil

  26. Rajasekhar says:

    I getting error like

    error Permission denied to get property Window.document

    What is the reason .please help me this is very urgent

  27. Dennis says:

    Firebug and YUI logger are your friends.

  28. Sasanka says:

    Hi,

    Thanks for the detailed guideline of YUI image upload functionality.

    I am using the java servlet example. But I am not able to upload files because
    the request object is not getting mapped with the insertimage_upload html file element.

    I am using yui-image-uploader26.js and kept all other things as instructed.

    Please advice.

    Thanks and Regards
    Sasanka

  29. measaura says:

    Great post! Anyhow, I’ve managed to use the yui-image-uploader26.js with RTE version 2.7. Maybe If I have more time, I’ll add the upload progress into the script.

  30. Rajasekhar says:

    Hi,

    I am using rte image uploader.
    i am unable to get the response after the image is uploaded to given folder.

  31. Rajasekhar says:

    when form submitted response is inserted to iframe.

    in connection.js
    uploadFile:function(o, callback, uri, postData)

    in this method i am unable to get the response.

    Mianly i am using this in ning opnesocial application.

    please help me on this issue.this is very important for me.

    target iframe is getting created and removed .then how can i get the response

    thank
    Rajasekhar

  32. Rajasekhar says:

    try
    {
    // responseText and responseXML will be populated with the same data from the iframe.
    // Since the HTTP headers cannot be read from the iframe
    console.log(io);
    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;
    }
    catch(e)
    {
    alert(e.message);
    }

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

  33. Øyvind says:

    Im trying this RTE with pic upload… but im still getting the same problem i had with the other version…

    The image gets uploaded, but the “Image URL” just “reloads”

    I see it changes, but in a sec, it returns to “Image URL Here”

    How can i fix this?

    Thanks

  34. Dennis says:

    Everybody’s situation is slightly different. Different browsers, different Operating systems etc. Only thing I can suggest is to user FireBug w/ Firefox and enable YUI logging.

  35. Pingback: An Image Upload Extension for YUI Rich Text Editor | All My Brain

  36. dodo says:

    Hi Dennis,
    Its fantastic script!
    What should i add in script that after user select image, the image panel will close auto?

  37. andy says:

    Hi Dennis,

    You RTE is very useful. One problem I faced today is when I upload an image which is about 2M. it took too long and quickly filled up my server space. Do you think you can provide resizing option in yui_image_uploader.php file?

    I tried to add resizing php code in your uploader.php, but it didn’t work.

  38. andy says:

    Here is my crop_image.php. I know how to add this to yui_image_uploader.php. However, somehow it doesn’t pass image_url to connection manager. the php file is heavenly tied to javascript and json which i don’t know. can anyone help?

    function getExtension($str) {

    $i = strrpos($str,”.”);
    if (!$i) { return “”; }

    $l = strlen($str) – $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }

    $errors=0;

    if($_SERVER[“REQUEST_METHOD”] == “POST”)
    {
    $image =$_FILES[“file”][“name”];
    $uploadedfile = $_FILES[‘file’][‘tmp_name’];

    if ($image)
    {
    $filename = stripslashes($_FILES[‘file’][‘name’]);
    $extension = getExtension($filename);
    $extension = strtolower($extension);

    if (($extension != “jpg”) && ($extension != “jpeg”) && ($extension != “png”) && ($extension != “gif”))
    {
    echo ‘ Unknown Image extension ‘;
    $errors=1;
    } else {
    $size=filesize($_FILES[‘file’][‘tmp_name’]);

    if($extension==”jpg” || $extension==”jpeg” )
    {
    $uploadedfile = $_FILES[‘file’][‘tmp_name’];
    $src = imagecreatefromjpeg($uploadedfile);
    }
    else if($extension==”png”)
    {
    $uploadedfile = $_FILES[‘file’][‘tmp_name’];
    $src = imagecreatefrompng($uploadedfile);
    }
    else
    {
    $src = imagecreatefromgif($uploadedfile);
    }

    list($width,$height)=getimagesize($uploadedfile);

    $newwidth=720;
    $newheight=($height/$width)*$newwidth;
    $tmp=imagecreatetruecolor($newwidth,$newheight);

    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,

    $width,$height);

    $ran = rand ();
    $filename = “test_images/cropped_”.$ran.”_”.$_FILES[‘file’][‘name’];

    imagejpeg($tmp,$filename,100);

    imagedestroy($src);
    imagedestroy($tmp);
    }//else
    }//if($image)
    }//if($server
    //If no errors registred, print the success message

    echo “I got here”;

    if($_SERVER[“REQUEST_METHOD”] == “POST” && !$errors)
    {
    // mysql_query(“update SQL statement “);
    echo “Image Uploaded Successfully!”;

    }

  39. Dennis says:

    I’m afraid resizing on the client side is something that is going to be a real pain with JavaScript. Perhaps it can be done but if so I don’t know how. I don’t think could do it unless you were using a browser extension or a plugin. Flash or Java could probably do it.

    Anyway, beyond the scope of this project anyway I think.

Comments are closed.