Codeigniter 3上传多张图片重命名文件

Upload multiple pictures renaming files in Codeigniter 3

我无法弄清楚我的代码有什么问题。

在我的项目中,允许用户为每个飞机注册号上传多张图片;我想用以下规则重命名每个上传的文件:注册id,减号,累进号;所以如果用户上传注册id为xxx的新图片文件,上传的文件名就变成xxx-1.jpg

上传多个文件的代码如下;到目前为止一切正常...

// Count uploaded files
$countfiles = count($_FILES['files']['name']);
// Define new image name
$image = $id . '-1.jpg';

for($i=0;$i<$countfiles;$i++)
{
    if(!empty($_FILES['files']['name'][$i]))
    {
        // Define new $_FILES array - $_FILES['file']
        $_FILES['file']['name'] = $_FILES['files']['name'][$i];
        $_FILES['file']['type'] = $_FILES['files']['type'][$i];
        $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
        $_FILES['file']['error'] = $_FILES['files']['error'][$i];
        $_FILES['file']['size'] = $_FILES['files']['size'][$i];

        // Check if the image file exist and modify name in case
        $filename = $this->_file_newname($uploaddir,$image);
        
        // Set preference
        $config['upload_path'] = $upload_path; 
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = '5000';
        $config['file_name'] = $filename;

        //Load upload library
        $this->load->library('upload',$config); 
        $arr = array('msg' => 'something went wrong', 'success' => false);
        // File upload
        if($this->upload->do_upload('file'))
        {
            $data = $this->upload->data(); 
        }
    }
}

_file_newname() 函数执行文件重命名操作,这里是代码:

private function _file_newname($path, $filename)
{
    if ($pos = strrpos($filename, '.')) {
        $name = substr($filename, 0, $pos);
        $ext = substr($filename, $pos);
    } else {
        $name = $filename;
    }
    $newpath = $path.$filename;
    $newname = $filename;
    if(file_exists($newpath)){
        $counter = 1;
        if($pos = strrpos($name, '-')) {
            $oldcounter = substr($name, $pos + 1);
            if(is_numeric($oldcounter)){
                $counter = $oldcounter++;
                $name = substr($name, 0, $pos);
            }
        }
        $newname = $name . '-' . $counter . $ext;
        $newpath = $path . $newname;

        while (file_exists($newpath)) {
            $newname = $name .'-'. $counter . $ext;
            $newpath = $path.$newname;
            $counter++;
        }
    }
    return $newname;
}

现在...问题...如果用户每次上传一个文件,重命名功能可以正常工作...所以第一次上传设置文件名 xxx-1.jpg,第二次上传将文件名设置为 xxx-2.jpg 等等……但是……如果用户一次上传不止一个文件……第二个文件变为 xxx-1x.jpg。 如果服务器上已经存在一个文件(例如 xxx-1.jpg )并且用户上传另外两个文件..它们被重命名为 xxx-2.jpg (正确)和 xxx-21.jpg (错了……应该是xxx-3.jpg).

有任何解决问题的提示或建议吗?

非常感谢

您的新文件名不适合上传的照片。 所以它变成静态的。

将该行放入循环中:

// 定义新图像名称 $图像 = $id 。 '-' 。 $我。 '.jpg';

这样您将保留 $id 并根据循环的迭代重命名文件 - $i.