So I'm trying out a very simple form with one field to upload an image. The input type is a file. There's a submit button also. The form has no action="" and the validation on the client side happens using the Jquery Validation plugin. Validation on the client side happens perfectly (It returns file type error), but as soon as I click upload, the upload is failing on the server side (PHP file). I don't think the file is being read on the server side since the if condition fails. My code is this:
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#upload").validate({
debug: false,
rules: {
file: {required: true, accept: "gif|png|jpg|jpeg"}
},
messages: {
file: "*Please select a file",
},
submitHandler: function(form) {
// do other stuff for a valid form
var phpurl = 'upload_file.php';
$.post(phpurl, $("#upload").serialize(), function(data) {
alert(data);
});
}
});
});
</script>
The PHP Code:
<?php
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
{
if ($_FILES["file"]["error"] > 0)
{
print "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
print "Upload: " . $_FILES["file"]["name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
print $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
print "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
print "Invalid file";
}
?>
The ouput I receive as an alert - is always invalid file.
If I try the form without the Jquery validation and directly using the action="upload_file.php
method, it perfectly works. What is the problem?
HTML:
<form id="upload" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>