Welcome Guest, Not a member yet? Register   Sign In
Latavish's Multiple Image Upload with Thumbnail Generation
#11

[eluser]Leon Stafford[/eluser]
I've just used this with ever slightly modified default code from the User Guide to enable multi-file uploads. It produces multiple views of the results too.

Note: Check your uploads folder path if different than mine. Also, if rewriting your URLs, add the upload folder name to your .htaccess file or you may get errors.


Here is my upload.php file:

Code:
<?php

class Upload extends Controller {
    
    function Upload()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url','html'));
    }
    
    function index()
    {    
        $this->load->view('upload_form', array('error' => ' ' ));
    }

    function do_upload()
    {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '1000';
        
        $this->load->library('upload');
    //
     foreach($_FILES as $key => $value)
        {
            if( ! empty($key['name']))
            {
                $this->upload->initialize($config);
        
                if ( ! $this->upload->do_upload($key))
                {
                    $errors[] = $this->upload->display_errors();
                    
                    $this->load->view('upload_form', $error);
                }    
                else
                {
                    $data[$key] = array('upload_data' => $this->upload->data());
            
                    $this->load->view('upload_success', $data[$key]);
                    

                }
             }
        
        }
    //
    
        
    }    
}
?>

Here is my upload_form.php file:

Code:
<html>
<head>
<title>Upload Form</title>
</head>
<body>

<?php echo $error;?>

<?php echo form_open_multipart('upload/do_upload');?>

<input type="file" name="userfile" size="20" />
<br /><br />
&lt;input type="file" name="userfile2" size="20" /&gt;
<br /><br />
&lt;input type="file" name="userfile3" size="20" /&gt;
<br /><br />
&lt;input type="file" name="userfile4" size="20" /&gt;
<br /><br />
<br /><br />

&lt;input type="submit" value="upload" /&gt;

&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;

Here is my upload_success.php file:

Code:
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Upload Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

<h3>Your file was successfully uploaded!</h3>

<ul>
&lt;?php foreach($upload_data as $item => $value):?&gt;
<li>&lt;?php echo $item;?&gt;: &lt;?php echo $value;?&gt;</li>
&lt;?php endforeach; ?&gt;
</ul>
&lt;? if ($upload_data['file_name']):?&gt;

&lt;? echo img('uploads/'.$upload_data['file_name']);?&gt;

&lt;? endif;?&gt;

<p>&lt;?php echo anchor('upload', 'Upload Another File!'); ?&gt;</p>

&lt;/body&gt;
&lt;/html&gt;
#12

[eluser]Leon Stafford[/eluser]
I had a bit of trouble with the last script, so here is one which is working much better now.

There are many examples of either M,V or C in these forums, but I couldn't find one complete multi-uploader example which worked.

Hopefully this will save other CI beginners the hours I spent fiddling with this!

*haven't checked the error functionality of this yet

upload.php Controller file:

Code:
&lt;?php

class Upload extends Controller {
    
    function Upload()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url','html'));
    }
    
    function index()
    {    
        $this->load->view('upload_form');
    }

    function do_upload()
    {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '3000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        
        $this->load->library('upload', $config);
    
        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
            
            $this->load->view('upload_form', $error);
        }    
        else
        {
            $data = array('upload_data' => $this->upload->data());
            
            //$this->load->view('upload_success', $data);
        }
    }    
        
    function multiple_upload($upload_dir = 'uploads', $config = array())
{
    $CI =& get_instance();
    $files = array();

    if(empty($config))
    {
        $config['upload_path']   = realpath($upload_dir);
        $config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
        $config['max_size']      = '2048';
    }
        
        $CI->load->library('upload', $config);
        
        $errors = FALSE;
        
        foreach($_FILES as $key => $value)
        {            
            if( ! empty($value['name']))
            {
                if( ! $CI->upload->do_upload($key))
                {                                          
                    $data['upload_message'] = $CI->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
                    $CI->load->vars($data);
                        
                    $errors = TRUE;
                }
                else
                {
                    // Build a file array from all uploaded files
                    $files[] = $CI->upload->data();
                    
                }
            }
        }
        
        // There was errors, we have to delete the uploaded files
        if($errors)
        {                    
            foreach($files as $key => $file)
            {
                @unlink($file['full_path']);    
            }                    
        }
        elseif(empty($files) AND empty($data['upload_message']))
        {
            $CI->lang->load('upload');
            $data['upload_message'] = ERR_OPEN.$CI->lang->line('upload_no_file_selected').ERR_CLOSE;
            $CI->load->vars($data);
        }
        else
        {
            
            $data = array('upload_data' => $files);
            
            $this->load->view('upload_success', $data);
        }
        
        
        
        
    }
}
?&gt;

upload_form.php View file:

Code:
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Upload Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;?php
        if(isset($upload_message))
        {
            echo $upload_message;
        }
    ?&gt;

&lt;?php echo form_open_multipart('upload/multiple_upload');?&gt;

&lt;input type="file" name="userfile1" size="20" /&gt;
<br /><br />
&lt;input type="file" name="userfile2" size="20" /&gt;
<br /><br />
&lt;input type="file" name="userfile3" size="20" /&gt;
<br /><br />
&lt;input type="file" name="userfile4" size="20" /&gt;
<br /><br />
<br /><br />

&lt;input type="submit" value="upload" /&gt;

&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;

upload_success.php View file:

Code:
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Upload Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

<h3>Your file was successfully uploaded!</h3>

<ul>
&lt;?php foreach($upload_data as $item => $value):?&gt;

&lt;?php
/*  EXAMPLE ARRAYS OUTPUT
[0] => Array   //access file_name with $value['file_name'] inside of &lt;?php foreach($upload_data as $item => $value):?&gt;
        (
            [file_name] => main9.jpeg
            [file_type] => image/jpeg
            [file_path] => E:/xampp/htdocs/igniter/uploads/
            [full_path] => E:/xampp/htdocs/igniter/uploads/main9.jpeg
            [raw_name] => main9
            [orig_name] => main.jpeg
            [file_ext] => .jpeg
            [file_size] => 4.58
            [is_image] => 1
            [image_width] => 160
            [image_height] => 90
            [image_type] => jpeg
            [image_size_str] => width="160" height="90"
    )

[1] => Array
    (
        [file_name] => Sunset.jpg
        [file_type] => image/jpeg
        [file_path] => E:/xampp/htdocs/igniter/uploads/
        [full_path] => E:/xampp/htdocs/igniter/uploads/Sunset.jpg
        [raw_name] => Sunset
        [orig_name] => Sunset.jpg
        [file_ext] => .jpg
        [file_size] => 69.52
        [is_image] => 1
        [image_width] => 800
        [image_height] => 600
        [image_type] => jpeg
        [image_size_str] => width="800" height="600"
    )
*/

?&gt;

<li>&lt;?php echo $value['file_name']; //outputs each files details as array?&gt;</li>



&lt;?php endforeach; ?&gt;
</ul>






<p>&lt;?php echo anchor('upload', 'Upload Another File!'); ?&gt;</p>

&lt;/body&gt;
&lt;/html&gt;
#13

[eluser]Leon Stafford[/eluser]
Here's another example for people searching.

This one's errors are working and the class is set up to be more modular for saving form results with multiple uploads and be re-useable for multiple forms by changing config arrays:

class file:

Code:
&lt;?php
class Save extends Controller {
    public $results = array();
    function Save()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url','html'));
        $this->load->library('form_validation');
    }
    
    function index()
    {    
        
        $this->load->view('upload_form');    
    }

    function file_upload()
    {
        
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '3000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        $this->load->library('upload', $config);
        $number_of_files = 4;
        
        for ($file_counter = 0; $file_counter < $number_of_files; $file_counter +=1){
            $this->upload->initialize($config);
            if ( ! $this->upload->do_upload('userfile'.$file_counter))
            {
                $this->results['result'.$file_counter]['error'] = array($this->upload->display_errors('<p style="color:red;">', '</p>'));
                $this->results['result'.$file_counter]['success'] = array('');
            }    
            else
            {
                $this->results['result'.$file_counter]['success'] = array($this->upload->data());
                $this->results['result'.$file_counter]['error'] = array('');
            }
        }
        
    }
    public $validation_config = array();
    public $shop_validation = array(
               array(
                     'field'   => 'username',
                     'label'   => 'Username',
                     'rules'   => 'trim|required|prep_for_form'
                  ),
               array(
                     'field'   => 'password',
                     'label'   => 'Password',
                     'rules'   => 'trim|required|matches[passconf]|md5'
                  ),
               array(
                     'field'   => 'passconf',
                     'label'   => 'Password Confirmation',
                     'rules'   => 'trim|required'
                  ),  
               array(
                     'field'   => 'email',
                     'label'   => 'Email',
                     'rules'   => 'trim|required|valid_email'
                  )
            );

    
    function validate_form()
    {
        $this->form_validation->set_error_delimiters('<p style="color:red;">', '</p>');
        $this->form_validation->set_rules($this->validation_config);        
                
        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('upload_form', $this->results);
        }
        else
        {
            $this->load->view('form_success');
        }
        
    }
    function save_shop()
    {
    $this->file_upload();
    $this->validation_config = $this->shop_validation;
    $this->validate_form();
    }
}
?&gt;

view file:

Code:
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Upload Form&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
HTML code starts here


&lt;?php
$total_files = 4;
?&gt;

&lt;?php
$attributes = array('class' => 'email_form', 'id' => 'upload_form');
echo form_open_multipart('save/save_shop',$attributes);?&gt;
&lt;!-- add for X do Y loop to set all image sections dynamically re number of file fields --&gt;
&lt;?php for ($x = 0; $x < $total_files; $x++){?&gt;
&lt;input type="file" name="userfile&lt;?php echo $x; ?&gt;" size="20" /&gt;
<br />
&lt;?php     if (isset(${"result$x"})){
            if (${"result$x"}['error'][0]!=''){
                //display error
                echo ${"result$x"}['error'][0];
            } else {
                echo ${"result$x"}['success'][0]['file_name'];
            }
            
            
        }?&gt;
<br /><br />
&lt;?php } ?&gt;
<h5>Username</h5>
&lt;?php echo form_error('username'); ?&gt;
&lt;input type="text" name="username" value="&lt;?php echo set_value('username'); ?&gt;" size="50" /&gt;

<h5>Password</h5>
&lt;?php echo form_error('password'); ?&gt;
&lt;input type="text" name="password" value="&lt;?php echo set_value('password'); ?&gt;" size="50" /&gt;

<h5>Password Confirm</h5>
&lt;?php echo form_error('passconf'); ?&gt;
&lt;input type="text" name="passconf" value="&lt;?php echo set_value('passconf'); ?&gt;" size="50" /&gt;

<h5>Email Address</h5>
&lt;?php echo form_error('email'); ?&gt;
&lt;input type="text" name="email" value="&lt;?php echo set_value('email'); ?&gt;" size="50" /&gt;


&lt;!-- change array structure so that fields are always created, just empty so can call directly without isset --&gt;
<br />

&lt;input type="submit" value="upload" /&gt;

&lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;
#14

[eluser]e-mike[/eluser]
Please see Single, Multiple and Multiple array upload library for a solution (hopefully soon)...
#15

[eluser]Leon Stafford[/eluser]
Scrap my above workings,...

I found SWFupload to be much better at handling unlimited uploads while showing progress if needed.

I tested in a non-CI site first to make sure I understood how it worked, then read these forums and had it working pretty quickly.

+1 rating from me :cheese:
#16

[eluser]Santiag0[/eluser]
The original code not work for me, but here is my simplified working adaptation

Code:
class multiupload extends Controller
{

function index()
{
            $config['upload_path'] = './content/img/photos';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size']    = '2048'; //2 meg
            $config['encrypt_name']    = TRUE;
            $this->load->library('upload', $config);
            $this->load->library('image_lib');
            //Upload error flag
            $error = FALSE;

            foreach($_FILES as $key => $value)
            {
                if( !empty($value['name']))
                {
                    if ( $this->upload->do_upload($key) )
                    {
                        $uploaded = $this->upload->data();

                        //Creat Thumbnail
                        $config['image_library'] = 'GD2';
                        $config['source_image'] = $uploaded['full_path'];
                        $config['create_thumb'] = TRUE;
                        $config['thumb_marker'] = '_tn';
                        $config['master_dim'] = 'width';
                        $config['quality'] = 75;
                        $config['maintain_ratio'] = TRUE;
                        $config['width'] = 175;
                        $config['height'] = 175;

                        $this->image_lib->clear();
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();

                        $imagename = $uploaded['file_name'].'_tn'.$uploaded['file_ext'];
                        $timestamp = time();

                        //Add Pic Info To Database
                        $this->db->set('file', $imagename);
                        //$this->db->set('date', $timestamp);

                        //Insert Info Into Database
                        $this->db->insert('photos');
                    }
                    else
                    {
                        $error = TRUE;
                    }
                }
            }
//If we have some error...
if($error) $this->session->set_flashdata('notice', '<div class="error icon"><ol>'.$this->upload->display_errors('<li>','</li>').'</ol></div>');

else $this->session->set_flashdata('notice', '<p class="success icon">¬°Success!</p>');

//Call the view
$this->load->view('upload_photos');
}
}
View file

Code:
&lt;?php
echo $this->session->flashdata('notice');
echo '<h3>Upload multiple photos</h3>';
echo form_open_multipart('multiupload');
?&gt;
  &lt;input type="file" name="p1" size="20" /&gt;
    &lt;input type="file" name="p2" size="20" /&gt;
    &lt;input type="file" name="p3" size="20" /&gt;
<button type="submit" name="send-photos" id="send-photos">Send</button>
&lt;/form&gt;

Enjoy and say 'thaks' if you find handy Wink

Thanks!
#17

[eluser]e-mike[/eluser]
Santiag0, see my post for Single, Multiple and Multiple array upload library...

http://ellislab.com/forums/viewthread/110130/

This lib is an extended version which works the same way as the original but than also with multiple upload.
#18

[eluser]Santiag0[/eluser]
Wow, looks great, I will check it out. Thanks a lot Mike!
#19

[eluser]cybercy[/eluser]
[quote author="Leon Stafford" date="1239615398"]Scrap my above workings,...

I found SWFupload to be much better at handling unlimited uploads while showing progress if needed.

I tested in a non-CI site first to make sure I understood how it worked, then read these forums and had it working pretty quickly.

+1 rating from me :cheese:[/quote]

Can you give us an example how you applied it, please?
It would be great.

Thank you
#20

[eluser]Shanto[/eluser]
Nice Script, Thanks for Sharing :-)




Theme © iAndrew 2016 - Forum software by © MyBB