Ajax File Upload


The secret to ajax file uploading is called target.

The main "problem" of uploading files is that you cannot set the value of a file input by javascript (this is a security precaution, else any website could download any file from your computer by just visiting a website). Thus you have to wait until the user manually chose a file before uploading. And even then, you're restricted to the actual form because the complete file is hidden from you (except in IE, but give it time...). And the default action of any form submission is a full page reload.

The trick then is that you can block the reloading of the current page on form submit by setting the target property of the form tag (which acts the same as it would on an anchor tag). The target then becomes a static or dynamic hidden iframe with src=about:blank. You add an onload event to the iframe so you can inform the user the file is done uploading.

This way you can upload files in your page without reloading the entire webpage :)

Code: (HTML)