Jump to content

Checking filesize on upload using Javascript


playaz

Recommended Posts

Is it possible to check the filesize when a user uploads a file - for instance let says i want a form to only accept *.jpg, *.gif. *.zip and be a maximum of 2MB - how could this be achieved in javascript. If the file upload is greater than 2mb or isnt one of the accepted extensions i'd like an alert box presented to the user. Can anyone assist me :)

(or even in PHP if this isnt possible using javascript alone)

Thanks in advance :)
You cant with javascript however you can with PHP using this:

$_FILES['fileUploadFormNameHere'][size']

change fileUploadFormNameHere to the name you have named your upload form to. The above code returns the size of the file in bytes. To get the size in Megabytes you'll want to divide the size by 1024.

Have a read through [a href=\"http://uk2.php.net/manual/en/features.file-upload.php\" target=\"_blank\"]here[/a] on how to use the $_FILES superglobal array.

So to check the file size of an uploaded file you'll want to do this:
[code]$size = $_FILES['fileUploadFormNameHere'][size'];

if($size > 2097152)
{
    die('File size must not be over 2MB! Your file was ' . number_format(($size/1024/1024), 2) . 'MB');
}[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.