Image Uploads with 100% Less Suck. Guaranteed.
Using a little bit of jQuery we can upload images without the suck.
Note: This demo will rock your socks in all browsers.
Old and Busted
Select a file and click upload. Simple right? Except once I select my image I can no longer see what was selected. The name of the file is at the end of the input, and if the input is short, or the file path is deep, I'm not going to see anything useful. Assuming that I took the time to give my file a descriptive name, which I probably didn't because hey, it's an image, it should be self descriptive.
Now try this variation. We ditch the upload button in favor of a save button and fire the AJAX upload event as soon as a file is selected. The image is processed server side and a thumbnail is loaded onto the existing page. Doesn't that feel so much better?
We now have a visual representation (imagine that) of the image we selected. This is particularly useful in larger forms when many fields will be submitted with a single action. It allows the user to review the form before pressing save and see what image (or images) they selected.
Now let's break it down.
First we attach the the AjaxUpload behavior to our
file form element.
Next we specify where we want to post the AJAX upload to. We like to keep all our urls in our html document so we pass this url
action attribute of our
Set the name of the
file form element that will be posted to your server.
class to your preview div to indicate that the image is uploading. In our case we are applying a background image to the preview div.
We also need to
display: none; the
img tag in the preview div so that the loading background image is visible, also for a more subtle reason explained below.
When the image has been uploaded we need to do two things. First we need to set the
src attribute of our preview
img tag to the
new thumb. Secondly we need to remove the loading class. If we simply execute those things in that order then we will see an annoying
flicker of the old image when the loading class has been removed but the new image has not yet loaded.
We avoid this problem by waiting to remove the loading class until after the preview image's
load event fires. We also
listener after it had fired since we only wanted to capture this event once.
Lastly we set the source of preview image to the thumbnail our server just created. In this example the response from the AJAX call is just the thumbnails url as text. You could also return it in whatever fancy format you like.
Copyright ZURB, freely available for distribution under the MIT license.