我正在尝试使用php进行多个文件/图像上传,但我得到的只是我上传文件夹中的一个文件,表单是通过ajax发送的。这是我的代码:
<input type='file' id='_file' multiple="multiple" name="SelectedFile[]">
<input type='button' id='_submit' value='Upload!'>
和PHP
<?php
// Output JSON
function outputJSON($msg, $status = 'error'){
header('Content-Type: application/json');
die(json_encode(array(
'data' => $msg,
'status' => $status
)));
}
$count = 0;
...
// Success!
foreach ($_FILES['SelectedFile']['name'] as $f => $name) {
outputJSON('File uploaded successfully to "' . 'upload/' . $_FILES['SelectedFile']['name'][0] . '".', 'success');
$count ++;
}
JS
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if (request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
_progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);
request.open('POST', 'upload.php');
request.send(data);
我仍然有Unknown error occurred: []
答案 0 :(得分:0)
从die
功能中删除outputJSON
来电,然后使用echo
代替,它会在foreach
的第一个循环中终止脚本。
<强>更新强>
假设文件已正确上传并存储在$_FILES
数组中,则此代码输出应由js解析:
header('Content-Type: application/json');
$output = array();
foreach ($_FILES['SelectedFile'] as $f => $file) {
$output []= array(
'data' => 'File uploaded successfully to "' . 'upload/' . $file['name'],
'status' => 'success',
);
}
echo json_encode($output);