我尝试上传多个文件并将其上传好。但我也在检查错误(类型和大小)并捕获数组变量中的错误。当我选择,比方说,3个图像,其中一个有一些错误(尺寸超过允许和/或类型不允许)和第一个图像,然后其他两个图像也没有上传。如果有错误的文件是第二个,那么只有第一个上传,而当错误图像是最后一个,前两个上传。我试图做的是即使一个或多个图像中存在错误,其他有效图像也应该上传,无论选择它们的顺序如何。
这是我的剧本:
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(empty($errors))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
elseif(!empty($errors))
{
return $errors;
}
}
}
答案 0 :(得分:1)
在循环中,您已检查$error[]
。因此,当错误在第一个文件中时,阵列将不会为空,其他图像将不会上传。
尝试如下:
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[$key] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[$key] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[$key] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(!isset($errors[$key]))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
}
if(!empty($errors))
{
return $errors;
}
}
我已将错误消息数组从$errors[]
更改为$errors[$key]
并检查了相同内容。因此,如果您有4个文件输入,第1个和第3个有错误,那么第2个和第4个将上传,您将在第0个和第2个数组索引中出错。