文件上传和使用Codeigniter创建上传文件夹

时间:2013-12-18 07:56:50

标签: php codeigniter file-upload codeigniter-2 image-uploading

我在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;
        }
    }

所以这基本上是将图像上传到相册。此外,如果文件夹相册不存在,则会创建新相册。

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

如果在上传图片之前没有错误,那么创建相册文件夹是不是更有意义?如果是,我该如何修复?

3 个答案:

答案 0 :(得分:4)

您已设置标志以检查目录是否存在。我已经更改了您的代码,使其按照您的需要运行。

<?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;
    }
}

?>

答案 1 :(得分:1)

接受的答案不是正确的方式!!!

正确的方法是扩展上传库

代码:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * File Uploading Class Extension
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Uploads
 * @author      Harrison Emmanuel (Eharry.me)
 * @link        https://www.eharry.me/blog/post/my-codeigniter-upload-extension/
 */
class MY_Upload extends CI_Upload {

    /**
     * Validate Upload Path
     *
     * Verifies that it is a valid upload path with proper permissions.
     *
     * @return  bool
     */
    public function validate_upload_path()
    {
        if ($this->upload_path === '')
        {
            $this->set_error('upload_no_filepath', 'error');
            return FALSE;
        }

        if (realpath($this->upload_path) !== FALSE)
        {
            $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
        }

        if ( ! is_dir($this->upload_path))
        {
            // EDIT: make directory and try again
            if ( ! mkdir ($this->upload_path, 0777, TRUE))
            {
                $this->set_error('upload_no_filepath', 'error');
                return FALSE;
            }
        }

        if ( ! is_really_writable($this->upload_path))
        {
            // EDIT: change directory mode
            if ( ! chmod($this->upload_path, 0777))
            {
                $this->set_error('upload_not_writable', 'error');
                return FALSE;
            }
        }

        $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/',  $this->upload_path);
        return TRUE;
    }
}


如何使用:

只需创建application/libraries/MY_Upload.php并将上面的代码粘贴到其中。 这就是全部!


更多信息:


注意:

此扩展程序与CodeIgniter 3.x和2.x版本兼容。

答案 2 :(得分:0)

你拥有它的方式如果它不存在,它将始终生成目录。

回答你的问题..是的,在上传之前创建文件夹会更有意义。

尝试这个:

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 {
        // put if statements here.
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }

所以它看起来像这样:

if (!$this->upload->do_upload('imgfile')) { 
        // upload failed
        return array('error' => $this->upload->display_errors('<span>', '</span>'));
    } else {
        if (!is_dir('uploads')) {
        mkdir('./uploads', 0777, true);
    }
    if (!is_dir('uploads/'.$album)) {
        mkdir('./uploads/'.$album, 0777, true);
    }
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }

如果我理解正确,这应该做你想要的。

希望它有所帮助。