«

Asynchronous File Upload – YUI’s Approach

Posted on September 4, 2007
Filed Under Javascript | 68 Comments     


Download YUI
Test upload example online
Online Example Source

YUI is a truly amazing framework for those who are writing Ajax applications. Its JavaScript widgets allow programmer to create richly interactive UI components with ease. However, these UI widgets are not very useful unless the end result of the interaction can be saved to the server side. Hence YUI has added Ajax support to most of its widgets. While many people are familiar with YUI Connection Manager's Ajax capability, only a few know that Connection Manager can be used to simulate Ajax-like file upload.

The theory that makes asynchronous file upload work is not complicate, but the code for it to work can be a little bit lengthy if it was developed from the scratch. Since there no reason to reinvent the wheel and YUI's Connection Manager can take care of most of the dirty jobs for us, in this article, I'll show you how to use it to do a simple asynchronous file upload. Because XMLHttpRequest object does not support file upload, the Connection Manager uses inline frame approach. Basically what the Connection Manager does is it creates an invisible IFRAME for file upload and parses the server response once the upload is completed. In the end, what you get is an illusion of Ajax-like file upload interaction. However, since this is an IFRAME, some Ajax events such as success or failure are not available in IFRAME method as they are available in regular Ajax request in YUI.

Test upload example online

Preparation

This script uses YUI's Connection Manager, you can either download it to your hard drive or you can include it directly from YUI online repository.

Include the following JavaScript file to your HTML page:



or from YUI repository:


HTML Upload Form

Create an upload form as usual and assign the form field an id:

<form action="upload.php" enctype="multipart/form-data" method="post" id="testForm">
  <input type="file" name="testFile"/>
  <input type="button" id="uploadButton" value="Upload"/>
</form>

In above case, we've assigned the id testForm to our form.

Coding JavaScript

First, we need to create a event handler to handle the click event of the upload button:

Upload Button Handler:

var onUploadButtonClick = function(e){
  //this method is called when upload button is clicked
};
YAHOO.util.Event.on('uploadButton', 'click', onUploadButtonClick);

Call setForm method:

As soon as the user clicks on the upload button, we use Connection Manager to do the actual upload. In order to do so, we must let YUI know which form we are dealing with: we first call setForm method of the Connection Manager, supply the form ID we assigned earlier and set the second argument of the setForm to true to indicate that this is a file upload request.

YAHOO.util.Connect.setForm('testForm', true);

Establish an Asynchronous Request:

Now, we are ready to upload files. Invoke asyncRequest method of the Connection Manager and specify request method as 'POST', the URL where files upload to, and the upload handler. The upload handler is an JavaScript associative array, in which the array key specifies type of event to handle and the array value is a callback function with signature function(response){}.

Since this is a file upload request, we need to handle the upload event. Here's how: in the upload handler, create a key-value pair with "upload" as key and a callback function as value. The callback function will be invoked when the server response is returned. For more information about upload handler, please see Callback Object and File Upload

The argument of the callback function, in this case response, contains information of server response. You can access text contents returned from the server after a file upload request by response.responseText or response.responseXML if the content type is XML. For more information, please visit Connection Manager Upload Case.

var uploadHandler = {
  //handle upload case. This function will be invoked after file upload is finished.
  upload: function(response) {
    alert(response.responseText);
  }
};
YAHOO.util.Connect.asyncRequest('POST', 'upload.php', uploadHandler);

Writing Server-Side Code

Your can write your server-side code in any programming language. For demonstration purpose, we will use PHP to handle file upload request. Since this is not an PHP file upload tutorial, I wrote an one line code snip that shows information of an uploaded file. You can use this information to confirm that whether a file has been successfully uploaded or not:

  print_r($_FILES);

If everything has gone well and you have this line alert( response.responseText ); in your upload handler (a handler is just a JavaScript function), you should see a message box similar to the one shown below, which indicates the file has been successfully uploaded:

File Upload Response

Putting Everything Together

<html>
<head>
<title>YUI File UploadS</title>



</head>
<body>

<form action="upload.php" enctype="multipart/form-data" method="post" id="testForm">
<input type="file" name="testFile"/>
<input type="button" id="uploadButton" value="Upload"/>
</form>

</body>
</html>

Related Reading

Links

If you find this post useful, consider donating a few bucks to help the server running cost.

Go to Top

More interesting posts ...

Subscribe to keep track of your comment.
68 Comments so far
  1. egor September 4, 2007 10:47 pm
    can you show upload.php source?
  2. Rob September 6, 2007 10:42 am
    What about Form Validation?
  3. Cuong September 6, 2007 11:35 am
    To egor:
    As stated in the article, upload.php consists only one line of code, which prints out human-readable text of PHP special variable $_FILES array:

    <?php
    print_r($_FILES);
    ?>

    You can use this information to verify whether a file is uploaded or not:

    <pre>
    Array
    (
    [file] => Array
    (
    [name] =>
    [type] =>
    [tmp_name] =>
    [error] => 4
    [size] => 0
    )

    )


    Above is a PHP response of @print_r($_FILES);@ without uploading a file. As you can see, @name@ and @tmp_name@ is empty in this case.

    You can retrieve the content of this response from your JavaScript code by using @response.responseText@ in your upload handler.

    Cheer!

    To Rob:
    I didn't quite get it what you mean. Can you be more specific?
  4. Rob September 12, 2007 10:53 am
    Do you think there would be an easy way to be ablt to Select Multiple files and then upload them?
  5. Rob September 12, 2007 11:03 am
    on Validation:
    If file has not been selected show an error
    if file is a certain format: EG jpg,gif etc.
    If other form fields are not enetered.

    Most upload form will have a title description etc
  6. Alex Vogt September 12, 2007 2:32 pm
    Doing it like this for years from now, long before the phrase "AJAX" popped up ;) with a little difference:

    Im using a JS callback from the Iframe, which i consider a bit more elegant than the $_FILES thingie..

    imagine PHP behind the iframe prints out a little , calling back to a function in the original page, giving some status information via parameter (upload status, actual file name after invalid characters stripped out, ... whatever comes to your mind)
  7. Alex Vogt September 12, 2007 2:33 pm
    i meant "print out a little [EVIL BRACKET]script[/EVIL BRACKET] ;)
  8. Jobin Basani September 13, 2007 12:28 am
    It works fine...exactly what I wanted..! Thanks a lot...
  9. Phoebe September 13, 2007 1:47 am
    If you find nothing is happening when you use he sample code, it may be because the sample at the end of this article assumes you have downloaded the YUI code and amended the path accordingly. If you want to use the YUI server version just change this:




    to

  10. Phoebe September 13, 2007 1:48 am
    Comment above stripped out the code, but I'm sure you can work out the change!
  11. Cuong September 13, 2007 6:49 am
    To Rob:

    bq. Do you think there would be an easy way to be ablt to Select Multiple files and then upload them?

    I really don't think you can select multiple files for upload merely from HTML. However, you can create multiple upload filed, i.e., @<input type="file" name="testFile"/>@ and upload them in one IFRAME request.

    bq. on Validation:
    If file has not been selected show an error
    if file is a certain format: EG jpg,gif etc.
    If other form fields are not enetered.

    Actually I have validated those on the server side. You can test my online upload example, it displays an alert box if no file has been uploaded or the format is not allowed.
  12. yuan September 13, 2007 10:05 pm
    exactly what I wanted... thanks a lot...
    it will be perfect if there's a process bar...
    can you show online demo source
  13. Cuong September 17, 2007 8:01 pm
    Here's the code for upload in PHP. I removed session management code since it's irrelevant and it reveals too much server detail:

    http://thecodecentral.com/wp-content/uploads/2007/09/upload.zip


    More about php file upload: http://us3.php.net/features.file-upload

    Encoding Json in PHP: http://thecodecentral.com/2007/09/13/easy-json-encodingdecoding-in-php
  14. yuan September 18, 2007 7:40 am
    thanks :)
  15. Fimana October 2, 2007 1:10 am
    awesome...
    thanks for the tutorial, i will try it..
  16. Decbrad October 3, 2007 1:54 pm
    Hi there... excellent feature! Just wondering if there's an .asp version of upload.php.

    Thanks in advance
    Decbrad
  17. Cuong October 4, 2007 7:20 am
    Sorry I don't have one for asp, but if you already know how to handle file upload in asp, then you are set.

    Just handle the upload request like any ordinary file upload request, and output some server responses to indicate the status of the upload, e.g., "upload success" or "file size is too large." The format can be text, HTML, XML or JSON. You have complete control on how to encode the server response.

    You can intercept the server response in your upload handler by this line @response.responseText@. It's then up to you what to do with this response.
  18. Grzyb9k October 11, 2007 5:50 am
    I want to show at the same page the list with links to files which i upload. How i can do that?
  19. Cuong October 11, 2007 9:57 am
    1) Save those links to an array so you can iterate through them.
    2) Create a DIV tag somewhere in the page.

    Assuming that you give this DIV an ID called "linkContainer", in your upload handler, you can write something like this:

    <pre>
    var con = document.getElementById("linkContainer");

    for(var i in links){
    var aTag = document.createElement("a");
    aTag.href = links[i].href;
    aTag.appendChild(document.createTextNode(link[i].text);
    con.appendChild(aTag);
    con.appendChild(document.createTextNode("br");
    }


    Added:
    Similar code is usde in "online demonstration":http://test.thecodecentral.com/demos/asyncupload/, you can take a look that as well.
  20. Grzyb9k October 11, 2007 10:02 am
    I dont understand.... :/
  21. Jav October 21, 2007 2:18 am
    Is it possible to do this kind of async upload, without the browser showing its reload progress bar - it would be more pretty:)
  22. mfogg November 12, 2007 11:56 am
    Thanks for this. I used it to upload an image and then display the image in the same window. On IE it works fine. On Safari the back button becomes active as if the page had refreshed. If the back button is clicked the image is permanently lost. Is this related to the iframe? Any idea how this can be fixed? Thanks again...
  23. david November 14, 2007 4:36 pm
    I understand how you are catching files which are too large on the server side, but i don't want to waste bandwidth.. is there a good way to filter them from the client side using YUI?
  24. Cuong November 20, 2007 1:37 pm
    \@Jav: I don't think so. This is an regular file upload that occurs behind an invisible IFRAME, so the browser will behave just like any other file upload.

    \@mfogg: Sorry I can't help you with this one since I don't have a Mac with me.

    \@david: JavaScript doesn't have the ability to access file system (excluding "ActiveX's FileSystemObject"http://www.codeproject.com/useritems/AJAXUpload.asp, but it is not cross-browser compatible), so you run out of luck. Not sure which server technology you are using, but if you can get the upload progress bar working for your technology, I believe you can terminate the upload inside of @updateProgress()@ function or whatever it called (it is the code segment that periodically sends upload progress back to the client).

    Another solution that I recently discovered is that through Flash, "more information":http://swfupload.mammon.se.
  25. paul December 28, 2007 5:18 am
    we want to see upload.php
  26. paul December 28, 2007 5:21 am
    oops i didn't know that question was already answered
  27. pan January 9, 2008 2:06 am
    Showing the content of listImages.php and image.php would also be helpful. plz
  28. Ontario January 9, 2008 7:00 am
    Why not just zip-up the contents of your online demonstration code and package it as a deliverable for all those curious folk (of which i am one), i too would like to see the contents of listImages.php and image.php
  29. Cuong January 11, 2008 7:06 pm
    Good call, here's the zip file:

    http://thecodecentral.com/wp-content/uploads/2008/01/asyncupload.zip
  30. DavidTan January 13, 2008 10:52 pm
    Just what I need. Thanks a lot :)
  31. Ontario January 14, 2008 5:05 am
    Kudos Cuong, really good code.
  32. dave chan January 19, 2008 12:52 am
    please kindly show the code in reset.php:P
  33. Cuong January 21, 2008 4:14 pm
    @dave:

    I believe I posted that 2 posts above your post. :||
  34. dinesh January 24, 2008 10:47 pm
    How do upload a doc file on server and then again open in it RTE?
    ex Suppose user from RTE user wants to upload a doc file on server then after processing this file from server again it should display in RTE.
    Then he can able to save it on his hard drive.
  35. Cuong January 29, 2008 11:24 am
    @dinesh

    First of all, what is RTE? I suppose it stands for Rich Text Editor. In spite of what kind of text editor you use, the procedure for asynchronous upload remains the same.

    Basically, on client-side, you need a file upload form that let the user to upload the doc file, and use YUI to do background uploading. In your upload handler, you need to listen to upload event, this is where you display processed result returned from the server.
    <pre>
    var uploadHandler = {
    //handle upload case. This function will be invoked after file upload is finished.
    upload: function(response) {
    //content of the doc file shall be response.responseText
    //use JavaScript to inject it into RTE
    }
    };


    On server-side, you need a write a script to handle uploading of the doc file, and you can do whatever server-side processing to the doc file in this script. After the file upload is completed, you need to output the content of this doc file in the format of your choice, which can be JSON, XML, HTML, so that the upload handler on the client-side can consume it.

    If you have doubt, take a look the source of online demonstration:
    http://thecodecentral.com/wp-content/uploads/2008/01/asyncupload.zip
  36. Gilberto Albino February 18, 2008 11:48 am
    Hey, It simply didn't work for me!
  37. [...] Asynchronous File Upload - YUI [...]
  38. vision March 2, 2008 12:57 pm
    very nice, if i get it to work i will use it in my next project
    ;-) www.spooXe.com
  39. links for 2007-09-11 March 31, 2008 6:45 am
    [...] Asynchronous File Upload - YUI&#8217;s Approach : Code Central (tags: AJAX YUI fileupload) [...]
  40. [...] Asynchronous File Upload / YUI [...]
  41. Dested July 10, 2008 12:50 pm
    Im going to leave a tidbit for all of us ASP.NET/c# developers. This is the best approach I have found (after days and days) for async file upload. To do this with .net I used a generic handler instead of a webservice. Using webservices it was being to finicky with format to do anything with the data. Just create Upload.ashx and in the ProcessRequest method use

    HttpContext postedContext = HttpContext.Current;
    HttpFileCollection Files = postedContext.Request.Files;


    You should be able to find your way around from there. If you set the
    in the web config you can upload any file. If there is trouble or questions I may upload an example, just ask.

    Thank you for this post, it saved me a great deal of work!
  42. gyxter July 24, 2008 3:29 am
    How come firebug says this error after i click upload "unexpected end of XML source"? I hope somebody could help me 'bout this. By the way, really nice work Cuong!:)
  43. DCapri July 25, 2008 12:04 pm
    Can anyone help me out here. The upload works great but Im having trouble getting the response code to say anything other than undefined.

    Ive written a .ashx ASP.Net and heres what I have server side.

    context.Response.ContentType = "text/plain"
    context.Response.Write("success")

    My upload handler only returns undefined.

    Any help would be greatly appreciated.
  44. apars July 28, 2008 1:27 pm
    I'm getting the same error as gyxter
  45. vijay August 1, 2008 3:10 am
    can anybody tell me that how i set path where i wanna to upload image??
    i wanna to use this uploader in jsp, anybody have code for it????
    Thanks a lot :)
  46. Julius August 14, 2008 1:56 am
    Would that be a better way to handle the form event?

    <pre>YAHOO.util.Event.on((formID here), 'submit', onUploadButtonClick);
  47. g00d August 14, 2008 7:19 pm
    hello guys.
    i`m novice. Can you show example in ASP? (Dested or someone)
  48. [...] AJAX upload For the AJAX upload, Code Central [...]
  49. sona October 31, 2008 9:37 am
    Where is the file uploaded to? How do I set the path to where the file is supposed to upload to?
  50. Felipe Ramirez November 25, 2008 6:37 am
    Hi, somebody know, How work all this with java?

    thanks

    HIPE
  51. Narkneesee December 19, 2008 6:24 am
    ??????? ?? ??????. ????????? ??? ??????
  52. ediptTex December 19, 2008 7:14 am
    ? ? ????????, ????, ??? ?????? ? ??? ?????, ?? ?????????? ??? ???? ??????.
  53. evisceviar December 19, 2008 8:07 am
    ??? ????? ??? ??????? ?????? ? ?????? ???? ???? ? ?????????? ????????. ????? ??????? ??? ??????? ?????????.
  54. anaepeDien December 20, 2008 3:40 am
    ???????? ????, ?? ????? ???????.
  55. RookReolueve January 5, 2009 11:11 am
    ????? ???????????? ???? ????????
  56. Top 100 AJAX with PHP Tahun 2007 - Get & Give February 12, 2009 11:02 pm
    [...] Asynchronous File Upload - YUI [...]
  57. [...] Asynchronous File Upload - YUI’s Approach [...]
  58. [...] AJAX upload For the AJAX upload, Code Central [...]
  59. vijay vinoth April 28, 2009 4:18 am
    Really its nice article.Thanks


    Regards,
    vijay
  60. [...] took the above code segment directly from a YUI file upload tutorial hence the credit goes to the author. The jsp back-end using apache commons file upload is as [...]
  61. Daniel September 10, 2009 9:58 am
    I have done it, however I cannot reach form fields nor querystrings and I don't know the reason. I'm using classic ASP. Does it happen in PHP? How do you catch input forms / querystrings sent with the file?
  62. [...] Furthermore, there&#8217;s no way of building a progress indicator using plain HTML forms without a pretty big amount of javascript + server-side trickery (a PHP solution | the YUI solution). [...]
  63. Alistair Stead November 23, 2009 9:06 am
    This example helped me narrow down the problems I was having. I made the mistake of trying to hijack the form submit event to send the asyncRequest.

    You need to use an alternate event to launch the request otherwise this fails.

    Here is my example:

    http://www.designdisclosure.com/2009/11/yui-connect-asynchronous-file-uploads/

    Regards

    Alistair
  64. sanu November 27, 2009 12:10 pm
    Hi, Nice demo, I have an issue using this in my web app as we are not allowed to do any other scripting language. Any idea how we do without PHP? can we have the code ported for Java?

    Thank you

    Sanu
  65. mmm January 26, 2010 1:14 am
    i have a problem. am trying to create a form having space for comments but am not able to output the comments at the bottom. help
  66. Bharathi January 28, 2010 10:47 pm
    Hi,
    I am trying to upload a text file like resume and read the data from that. is it possible using YUI?... if YES na How? any one can help me. i am a new one to YUI. Pls.
  67. gary February 17, 2010 8:32 am
    I can't get this to work so far I get to that point

    If everything has gone well and you have this line alert( response.responseText ); in your upload handler (a handler is just a JavaScript function), you should see a message box similar to the one shown below, which indicates the file has been successfully uploaded:
    I need to know what to do next and what changes i need to make in upload.php to make it work. Im a newbie
  68. gary February 17, 2010 8:35 am
    I can't get this to work so far I get to that point
    the page at http://localhost says....

    I need to know what to do next and what changes i need to make in upload.php to make it work. Im a newbie
Code Central Special

Polls

  • Your opinion about the design of this site:

    View Results

    Loading ... Loading ...