在CodeIgniter中使用ajax和php上传多个图像文件

问题描述 投票:0回答:1
php ajax codeigniter
1个回答
0
投票

实际上,代码中存在不止一个问题。首先,您应该将

$this->load->library('upload',$config)
语句从 for 循环中取出。您需要从列表中的每个文件创建单个文件才能上传。如果我没记错的话,Codeigniter
do_upload
方法不适用于多个文件。您可以像下面这样更新您的 uploadimg 方法:

private function uploadimg($images) {
    $uploadedFiles = array(); // captured uploaded file name

    $config = [
        'upload_path' => './testUploads/',
        'allowed_types' => 'jpg|jpeg|png|gif',
        'max_size' => 2048,
        'encrypt_name' => TRUE,
    ];
    $this->load->library('upload', $config);

    // Loop through each uploaded file
    for ($i = 0; $i < count($images['name']); $i++) {
        // Generate a unique file name or use the original name
        $originalFileName = $images['name'][$i];
        $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
        $file_name = uniqid() . '_' . $originalFileName;

        $config['file_name'] = $file_name;
        $this->upload->initialize($config);

        $_FILES['singleImage']['name']     = $file_name;
        $_FILES['singleImage']['type']     = $images['type'][$i];
        $_FILES['singleImage']['tmp_name'] = $images['tmp_name'][$i];
        $_FILES['singleImage']['error']    = $images['error'][$i];
        $_FILES['singleImage']['size']     = $images['size'][$i];
        

        // Perform the upload
        if ($this->upload->do_upload('singleImage')) {
            $uploadedFiles[] = $file_name;
        } else {
            // Handle the case where an upload failed
            return false;
        }
    }

    return $uploadedFiles;
}

P.S 我明白了,您正在生成一个更易读的文件名。如果您想查找具有该命名结构的文件,您应该将配置数组中的 encrypt_name 字段设置为 false。

© www.soinside.com 2019 - 2024. All rights reserved.