Codeigniter,上传多个同名文件

时间:2013-05-16 10:47:58

标签: php file codeigniter upload multiple-files

我有一个上传表单,允许我根据需要添加任意数量的文件。但是当我开始尝试上传文件时,我收到了一个错误。

控制器

$this->load->library('upload'); 
$error = "";
$file  = "";
$this->total_count_of_files = count($_FILES['user_certificates']['name']);
print_r($_FILES['user_certificates']['name']);

for($i=0; $i<$this->total_count_of_files; $i++)
{
    $_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
    $_FILES['user_certificates']['type'] = $_FILES['user_certificates']['type'][$i];
    $_FILES['user_certificates']['tmp_name'] = $_FILES['user_certificates']['tmp_name'][$i];
    $_FILES['user_certificates']['error'] = $_FILES['user_certificates']['error'][$i];
    $_FILES['user_certificates']['size'] = $_FILES['user_certificates']['size'][$i];

    $config['encrypt_name'] = TRUE;
    $config['file_name'] = $_FILES['user_certificates']['name'];
    $config['upload_path'] = './certificate_files/';
    $config['allowed_types'] = 'txt|pdf|doc|docx';
    $config['max_size'] = 0;

    $this->upload->initialize($config);

    if (!$this->upload->do_upload())
    {
        $status = 'error';
        $msg = $this->upload->display_errors();
    }
    else
    {
        $data = $this->upload->data();
        $file = $data['raw_name'] . $data['file_ext'];
    }
    if($file)
    {
        $status = "success";
        $msg = "Image successfully uploaded";
    }
    else
    {
        $status = "error";
        $msg = "Something went wrong when saving the image, please try again.";
    }
}   
echo json_encode(array('status' => $status, 'msg' => $msg));
exit();

print_r($_FILES['user_certificates']['name']))向我显示我添加的文件:

Array ( [0] => license.txt [1] => license.txt )

我完全不知道如何让上传工作。有什么想法吗?

提前干杯!

修改

如果我改变了这个:

if (!$this->upload->do_upload())

到此:

if (!$this->upload->do_upload('user_certificates'))

它可以工作,但仅适用于一个文件,它似乎不会因某种原因再次循环

1 个答案:

答案 0 :(得分:2)

您的循环似乎不正确。

...
$_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
...

这些行会覆盖原来的$ _FILES数组,因此在完成第一个循环后,它将无法在循环中找到任何其他内容,因为它被覆盖了。

相反,您可以先将$ _FILES数组存储到局部变量中,然后循环遍历它以逐个上传。