我想通過ajax上傳用戶註冊圖片。這是它看起來像表格+名稱,密碼和電子郵件的一些工作良好的字段。圖片上傳表格始終爲NULL
<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
<div class="form-group">
<label><b>Profile Image <span class="required">*</span></b></label>
<input accept="image/*" type="file" id="picture" name="picture" required>
</div>
<div class="clearfix">
<button type="submit" id="login" class="signupbtn">Sign Up</button>
</div>
</form>
我已經在另一個線程發現在這裏,這樣我需要把這個在我的AJAX腳本
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
而且這是整個AJAX
function submitForm()
{
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data=="registered")
{
}
}
});
return false;
}
而服務器端的圖片部分和查詢
if(!empty($_FILES['picture']) && $_FILES['picture']['size'] >0 ){
$profilePic = $randomString. basename($_FILES['picture']['name']);
$uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
} else {
$error = "error\n";
}
}else{
$error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
$stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(":email"=>$email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
$stmt->bindParam(":picture",$profilePic);
if($stmt->execute()) {
echo "registered";
}
else { echo "Query could not execute !"; }
}
else{ echo "1"; }
}
catch(PDOException $e){
echo $e->getMessage();
}
我已經刪除了其他字段,以便儘可能簡化代碼。除圖像名稱外,所有字段都已插入並保存在數據庫中。
可能是什麼問題?根本沒有錯誤。我在控制檯上有registered
,NULL爲var_dump($_FILES['picture'])
你不能使用簡單的ajax調用獲取文件。你可以看到這個網址。這一定會幫助你。 https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously/8758614#8758614 –
控制檯上仍然有'Null'。我已經添加到我的ajax,因爲這是我可以看到的差異︰'data:new FormData($('form')[0]),cache:false,contentType:false,processData:false,' – Ivan