Welcome Guest, Not a member yet? Register   Sign In
CI 1.7 multi file upload. Possible?
#3

I just wrapped up writing this section in my book, actually. I don't have a 1.7 codebase lying around, but I don't think it changed that much.

The issue is that CI's Upload library doesn't support multiple files with the same name. Additionally, the $_FILES array likely isn't structured like you expect it to be. See the official PHP docs for an example. The simplest solution that I could come up with was to modify the $_FILES array directly to have a unique file name and data in a way that the Upload library can deal with it. The following function will do that for you:

Code:
public function restructureFilesArray($files)
    {
        $new_files = array();

        foreach ($files as $name => $file)
        {
            $file_count = count($file['name']);
            $file_keys = array_keys($file);

            $temp = [];

            for ($i=0; $i < $file_count; $i++)
            {
                foreach ($file_keys as $key)
                {
                    $temp[$key] = $file[$key][$i];
                }

                $new_files[$name.$i] = $temp;
            }
        }

        return $new_files;
    }

You can then use it in your controller something like:

Code:
public function index()
    {
        if (! empty($_FILES))
        {
            $config['upload_path']          = APPPATH.'cache';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

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

            $_FILES = $this->restructureFilesArray($_FILES);

            foreach ($_FILES as $file => $arr)
            {
                if ( ! $this->upload->do_upload($file))
                {
                    echo "Unable to upload {$file}.<br/>";
                }

                echo "{$file} uploaded.<br/>";
            }
        }

        $this->load->view('uploads');
    }
Reply


Messages In This Thread
CI 1.7 multi file upload. Possible? - by frobak - 01-12-2016, 07:36 AM
RE: CI 1.7 multi file upload. Possible? - by kilishan - 01-12-2016, 01:56 PM



Theme © iAndrew 2016 - Forum software by © MyBB