通过ajax提交带有图像的表单

时间:2014-02-16 05:55:10

标签: php jquery ajax image image-uploading

我试图通过ajax上传图片,我知道我必须序列化它,但上传不是我的强项,我不确定我在上传部分做错了什么,我刚刚从http://www.w3schools.com/PHP/php_file_upload.asp获取了上传部分的代码。

这是我的所有代码:

形式

<div class="addschool" style="margin-top: 14px; display:none;">
<form class="form-add" role="form" onsubmit = "return aschool()" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" id="schoolname" placeholder="Name of School">
</div>
<div class="form-group">
<textarea class="form-control" rows="3" id="schoolabout" placeholder="About the School"></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Upload Syllabus</label>
<input type="file" id="file" name="file">
<p class="help-block">File type: png, jpg, jpeg, bmp</p>
</div>
<button type="submit" class="btn btn-default pull-right">Submit</button>
</form>
</div>

AJAX

function aschool(){
$.ajax({url:"upload.php", 
data: $(".form-add").serialize(),
cache:false,
type:'post',
success: function(data){
console.log(data);
if(data == 1){

}else{

}           
},
});
}

上传部分

<?php
require_once("header.php");
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>

0 个答案:

没有答案