Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).

2008-7-28

Ajax file upload notes

I'm just getting into the whole fake-Ajax file upload thing.

Interesting discovery: while you can't write to the value of an <input type="file"> element from Javascript, you can clone such elements into other forms and submit them. e.g. in jQuery:

$('#newform').append($('#somefileinput').clone()).submit()

This lets you submit the main form with an XMLHTTPRequest, but move the files off somewhere else to be uploaded in the background and associated with whatever content it was you just uploaded.

Update: If you're doing this in mootools, you'll need to call the DOM cloneNode() method rather than using mootools' clone(), as mootools clones by completely rebuilding the element. In code:

$('newform').grab($('somefileinput').cloneNode()).submit();