我正在使用HTML5的FormData和jQuery开发一个多文件上传器。我有以下代码:
$(function() {
$('#file').bind("change", function() {
var formData = new FormData();
//loop for add $_FILES["upload"+i] to formData
for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
formData.append("file" + i, document.getElementById('file').files[i]);
}
//send formData to server-side
$.ajax({
url : "file-upload.php",
type : 'post',
data : formData,
dataType : 'json',
async : true,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
error : function(request) {
alert('error!!');
console.log(request.responseText);
},
success : function(json) {
alert('success!!');
$('#upload-result')[0].append(json);
}
});
});
});
我可以看到我的file-upload.php
工作正常,因为文件已上传!但是为什么我的jQuery击中错误函数,而不是成功函数?我得到一个错误的警告。
#upload-result
。
PHP代码foreach($_FILES as $index => $file)
{
$fileName = $file['name'];
// echo '[ file name: ' . $fileName . ' - ';
$fileTempName = $file['tmp_name'];
// echo 'file temp name: ' . $fileTempName . ' ]';
if(!empty($file['error'][$index]))
{
// some error occured with the file in index $index
// yield an error here
return false; // return false also immediately perhaps??
}
// check whether it's not empty, and whether it indeed is an uploaded file
if(!empty($fileTempName) && is_uploaded_file($fileTempName))
{
// the path to the actual uploaded file is in $_FILES[ 'file' ][ 'tmp_name' ][ $index ]
// do something with it:
move_uploaded_file($fileTempName, "uploads/" . $fileName);
echo json_encode('<p>Click <a href="'. 'uploads/' . $fileName . '">here</a> to download file!</p>');
}
}
我明白了。我得到jQuery AJAX错误,即使我的状态码是200的php文件,因为我有我的dataType
作为JSON,而我返回简单的HTML。
dataType: 'html',
固定!
谢谢。