There are several javascript utilities available to provide you user with a pleasant way to upload files from the front end of your web application. My utility of choice today is wonderful jquery plugin called plupload. You can read more about plupload on their website.

What file upload utility you choose to use is up to you, my goal today is to present you with a little javascript code that will allow you to show an appropriate icon next to your freshly uploaded file. For example, pdf’s will show a pdf icon, and all images will show an image icon.


// use some regular expression goodness to match the appropriate file extension
var pattern=/\.[0-9a-z]+$/i;

// extract file extension 
var ext = (file.name).match(pattern);
ext = ext[0].toLowerCase();

// set default icon
var icon = 'http://'+window.location.hostname+'/js/plupload/img/attachment.png';

// check for pdf's
if( '.pdf' == ext){
 icon = 'http://'+window.location.hostname+'/js/plupload/img/pdf_file.png';
}// check for images
else if( '.jpg' == ext || '.gif' == ext || '.png' == ext || '.jpeg' == ext){
 icon = 'http://'+window.location.hostname+'/uploads/'+file.target_name;
}

// at this point you can check for other likely extensions, such as word doc, or excel files.

// display the icon
var thumb = '<div class="plupload_thumb"><a href="" title="" rel=""><img src="'+icon+'"></a></div>';