Monday, March 10, 2008

Asynchronous file uploads

Here is a screen-shot of the async file upload I talked about in the earlier post.
The iframe is the "Upload File" UI element. It is embedded in the main form.
The main form has no idea of there being a file input element. All the file input logic is in the form element within the iframe. This way the file upload can even be re-used in different forms.

In fact livemocha has 2 forms where users can upload pictures. The first is when the user activates their account, the next is when they later would want to edit their profile information. I use the iframe code for both of those views. And that includes the controler logic that processes the image as well.

GMail like Asynchronous file upload from a form

Web forms that allow you to upload files typically insist on clicking on a "Submit" button to upload the file to the web server.
Most input data can be submitted to the web server from the client using Ajax, thus bypassing a "Submit" button. However file data cannot be serialized and passed to the web server with Ajax.
It is possible to use Javascript (NOT Ajax) and call form.submit() directly, thus bypassing the "Submit" button.
The only issue here is that, we have no control over how the submit() call renders data. One specific issue is that this call would cause the whole form to re-load which results in the user losing any other data she may have entered on the same page.

It is possible to use an iFrame within the form, include the file input field within the iFrame and call iFrame.form.submit() to upload the file. Then only the iFrame will be re-loaded and the rest of the form will remain intact.

GMail uses a technique similar to this, that allows them to "see" the attachment before the user clicks "Send" on the email - this is a very useful feature, as users immediately get feedback, GMail can perform validations - eg: virus checks - on the file as the user is composing the email etc.

Examine the html at to get an idea

Notice the "src" parameter points to a different form for the file upload part. That is the mini-form that posts the file data asynchronously (using javascript) to the server.

The javascript does the direct submit to the webserver bypassing the "Submit" button - in fact the mini-form inside the iframe does not have a Submit button as you can see. The javascript is triggered via the "onchange" notification on the file input field, i.e: when a file is selected for upload by the user.

This is a feature that is now available at - check it out so you can see some more nice interactions. For example, you can immediately show the new picture uploaded to the user - normally this is difficult to do on the web browser, as on the client we have no access to the local file system.