Fileigniter上传文件并创建上传文件夹

ltd*_*dev 1 php codeigniter file-upload image-uploading codeigniter-2

我的Album_Model内部具有此功能:

public function upload($album_id, $album){
        $album= strtolower($album);

        $upload_config = array(
            'upload_path'   =>  './uploads/'.$album,
            'allowed_types' =>  'jpg|jpeg|gif|png',
            'max_size'      =>  '2000',
            'max_width'     =>  '680',
            'max_height'    =>  '435', 
        );

        $this->load->library('upload', $upload_config);

        // create an album if not already exist in uploads dir
// wouldn't make more sence if this part is done if there are no errors and right before the upload ??
        if (!is_dir('uploads')) {
            mkdir('./uploads', 0777, true);
        }
        if (!is_dir('uploads/'.$album)) {
            mkdir('./uploads/'.$album, 0777, true);
        }

        if (!$this->upload->do_upload('imgfile')) { 
            // upload failed
            return array('error' => $this->upload->display_errors('<span>', '</span>'));
        } else {
            // upload success
            $upload_data = $this->upload->data();
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

因此,这基本上是将图像上传到相册。另外,如果文件夹相册还不存在,它将创建一个新相册。

我正在做一些测试,发现可能是一个小错误。当我强迫表单进行一些无效的上载尝试并且上载失败时,正如预期的那样,但是仍然创建了相册文件夹(假设相册文件夹不存在)。

如果没有错误,并且在上载图像之前,谁也不会更想创建相册文件夹?如果可以,该如何解决呢?

Kum*_*r V 5

您已经设置了用于检查目录是否存在的标志。我已更改您的代码以使其根据您的需要工作。

<?php

public function upload($album_id, $album)
{
    $album = strtolower($album);

    $upload_config = array('upload_path' => './uploads/' . $album, 'allowed_types' =>
        'jpg|jpeg|gif|png', 'max_size' => '2000', 'max_width' => '680', 'max_height' =>
        '435', );

    $this->load->library('upload', $upload_config);

    // create an album if not already exist in uploads dir
    // wouldn't make more sence if this part is done if there are no errors and right before the upload ??
    if (!is_dir('uploads'))
    {
        mkdir('./uploads', 0777, true);
    }
    $dir_exist = true; // flag for checking the directory exist or not
    if (!is_dir('uploads/' . $album))
    {
        mkdir('./uploads/' . $album, 0777, true);
        $dir_exist = false; // dir not exist
    }
    else{

    }

    if (!$this->upload->do_upload('imgfile'))
    {
        // upload failed
        //delete dir if not exist before upload
        if(!$dir_exist)
          rmdir('./uploads/' . $album);

        return array('error' => $this->upload->display_errors('<span>', '</span>'));
    } else
    {
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }
}

?>
Run Code Online (Sandbox Code Playgroud)