【发布时间】:2014-10-14 21:15:36
【问题描述】:
我正在使用 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 echo 调用的结果!我想将其附加到#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>');
}
}
【问题讨论】:
-
你能说明错误是什么吗?
-
查看浏览器的开发者工具。重新加载页面。 JavaScript 控制台说什么?您能在 Net 选项卡中看到您的 Ajax 请求吗?格式是否正确?它得到回应了吗?回答正确吗?
-
可以打印request.responseText
-
jQuery错误函数的定义为:
Function( jqXHR jqXHR, String textStatus, String errorThrown )。 看第三个参数,jQuery报什么错误? -
使用控制台输出更新问题。
标签: php jquery ajax file-upload multipartform-data