我正在测试我的桌面test.xlsx
,test - Copy.xlsx
和test - Copy (2).xlsx
上的3个文件的上传内容。我的PHP脚本在我的move_uploaded_files
语句所在的行处断开。我收到错误move_uploaded_file(uploads/test - Copy.xlsx): failed to open stream: No such file or directory
。检查上传文件夹时,但 test - Copy (2).xlsx
已上传。我的PHP如下:
foreach($_FILES['file']['name'] as $key=>$value){
$fileName = $_FILES['file']['name'][$key];
$fileTmpLoc = $_FILES['file']['tmp_name'][$key];
$fileErrorMsg = $_FILES['file']['error'][$key];
$type = $_FILES['file']['type'][$key];
if(){
//validation
} else{ //if validated
if(move_uploaded_file($fileTmpLoc, 'uploads/'.$fileName)){
//do more stuff
} else{
echo "Upload failed.";
}
}
}
//为test - Copy (2).xlsx
执行更多内容实际运行一次(唯一成功上传的文件)。我的JS脚本在下面,但我怀疑这是因为我在PHP中使用print_r($ _ FILES)时所有文件都出现在输出中。
var upload = function(event){
var file = document.getElementById('file').files;
var data = new FormData();
for (i=0; i<file.length; i++){
data.append('file[]', file[i]);
}
var request = new XMLHttpRequest();
request.addEventListener('load', completeHandler, false);
request.addEventListener('error', errorHandler, false);
request.addEventListener('abort', abortHandler, false);
request.open('POST', 'php/excel_upload_read.php');
request.send(data);
};
我做错了什么?
答案 0 :(得分:1)
看起来您正在以错误的顺序使用多维数组。试试这个:
foreach($_FILES['file'] as $key=>$value){
$fileName = $_FILES['file'][$key]['name'];
$fileTmpLoc = $_FILES['file'][$key]['tmp_name'];
$fileErrorMsg = $_FILES['file'][$key]['error'];
$type = $_FILES['file'][$key]['type'];
...
}
答案 1 :(得分:1)
问题在于$_FILES
全局结构的方式,它不允许您轻松迭代。
您可以使用此功能来重新组织数据结构
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
然后你可以轻松使用foreach:
if(isset($_FILES['file']['tmp_name'], $_POST)) {
$files = reArrayFiles($_FILES['file']);
foreach ($files as $file) {
$temp = $file['tmp_name'];
$path = 'uploads/'.$file['name'];
if(move_uploaded_file($temp, $path)){
echo 'Upload succesful';
}else{
echo 'failed to upload';
}
}
}else{
echo 'file not uploaded';
}
此函数reArrayFiles
由PHP文档中的某人发布:
http://php.net/manual/en/features.file-upload.multiple.php