/    Sign up×
Community /Pin to ProfileBookmark

Ajax to check file size and type before uploading

Hi, I am trying to write a script that checks the size and type of a file as it is selected, without submitting the form:

<input name=”uploadedfile” type=”file” onchange=”ajax_check_image()”/>

The Ajax function basically looks like this:

//Opens and sends the ajax request
ajax_request.open(“GET”,”functions/check_image_file.php”,true);
ajax_request.send(null);

And then the script it calls looks like this:

<?php

//Checks if the image is the right file type and less than 100k.
if ((($_FILES[“uploadedfile”][“type”] == “image/gif”)
|| ($_
FILES[“uploadedfile”][“type”] == “image/jpeg”)
|| ($_FILES[“uploadedfile”][“type”] == “image/pjpeg”))
&& ($_
FILES[“uploadedfile”][“size”] < 100001))
{
//If
if ($_FILES[“uploadedfile”][“error”] > 0)
{
echo ($_
FILES[“uploadedfile”][“error”] . ” is an invalid image file”);
}
else
{
echo ($_FILES[“uploadedfile”][“name”] . ” is an valid image file”);
}
}
else
{
echo “Invalid file”;
}
?>

The problem is that the PHP $FILES[][] only picks up the files if it has been submitted from a form.

Is there anyway to check the file without submitting the form?

Thanks in advance.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meJul 25.2009 — only in firefox3 afaik...

the input provides a files[] array that can output a string version of the file, the length of which is about the same as the file size.

i think they may be a flash uploader that can let you check before you submit, but that's a question for another forum...

you might be able to get the pixel dimaensions of an image by setting an <img> tag's .src to the .value of the file input (but not in FF3+).
Copy linkTweet thisAlerts:
@coldscooterauthorJul 25.2009 — Ok thanks for the response. That helps alot.
Copy linkTweet thisAlerts:
@A1ien51Jul 26.2009 — setting the image with a local file will fail in almost any modern day browser for security reasons.

Eric
×

Success!

Help @coldscooter spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...