我正在使用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命中错误函数而不是成功函数?我收到错误提示。
在控制台窗口中,我看到了PHP回声调用的结果!#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>');
}
}
我想到了。即使我的php文件的状态代码为200,我仍然收到jQuery AJAX错误,因为我将自己的dataType
JSON作为JSON,而我返回的是简单的HTML。
dataType: 'html',
修复!
谢谢大家
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句