Saturday, August 09, 2008

Getting the file size before upload with Ajax

One of my new projects requires users to upload pictures to our service. The problem is that everybody and their mother has a 7.2 Mpx camera. After some wikipedia research i discovered that jpeg photos are encoded at maximum of about 8.25 bits/pixel. (don't write me about decimal point bit values please :) ).

So out came the pad of paper (and calculator)...

(7.2 * 10^6) * 8.25 = 594 * 10^5 [bits]

(594 * 10^5)/8 = 7425000 bytes or 7.1 Mb per picture

Now i wanted to limit the users to 1 Mb per picture, and wanted them to upload numerous ones at that. Now from a usability point of view it would be a "epic fail" if uncle Roy waited for 5 minutes while his picture uploaded, just to discover that we won't accept it because it's too big.

Now, I imagine your saying that this problem has been solved, it's called a flash uploader (or sliverlight depending on who you get your checks from). However there is a new solution, doing file size checking without flash, using only ajax.


Thats right ma, no flash. Firefox 3 has introduced something new to our world. It's called the filelist Object. Lying deep within in it is a property called (drum roll please) fileSize, and you can use it like so...


Javascript

//Only works in firefox 3
//i Used jquery to do a dom lookup
//However you could do the ol' fashioned window.document.getElementById()
fileSize = $('#fileInput')[0].files[0].fileSize;


It returns the size of file in bytes as an integer! 

Hopefully you've learnt something new, i certainly did. I have a plan to get a similar technique to work on all browsers, however at the moment i'm being thwarted by browser security issues :(.

You can get all the files over at the lab

Andrew Carnegie
A man who dies rich, is a man who dies shamed

No comments: