Part of the EllisLab Network
   
2 of 3
2
Latavish’s Multiple Image Upload with Thumbnail Generation
Posted: 08 February 2009 08:19 PM   [ Ignore ]   [ # 11 ]  
Grad Student
Rank
Total Posts:  53
Joined  02-06-2009

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:

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

upload_form.php View file:

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

<?php
        
if(isset($upload_message))
        
{
            
echo $upload_message;
        
}
    ?>

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

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

<
input type="submit" value="upload" />

</
form>

</
body>
</
html>

upload_success.php View file:

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

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

<
ul>
<?php foreach($upload_data as $item => $value):?>

<?php
/*  EXAMPLE ARRAYS OUTPUT
[0] => Array   //access file_name with $value['file_name'] inside of <?php foreach($upload_data as $item => $value):?>
        (
            [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"
    )
*/

?>

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



<?php endforeach; ?>
</ul>






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

</
body>
</
html>
 Signature 

Leon Stafford
China Dropship
Twitter Icons

Profile
 
 
Posted: 09 February 2009 03:36 AM   [ Ignore ]   [ # 12 ]  
Grad Student
Rank
Total Posts:  53
Joined  02-06-2009

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:

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

view file:

<html>
<
head>
<
title>Upload Form</title>
</
head>
<
body>
HTML code starts here


<?php
$total_files
= 4;
?>

<?php
$attributes
= array('class' => 'email_form', 'id' => 'upload_form');
echo
form_open_multipart('save/save_shop',$attributes);?>
<!-- add for X do Y loop to set all image sections dynamically re number of file fields -->
<?php for ($x = 0; $x < $total_files; $x++){?>
<input type="file" name="userfile<?php echo $x; ?>" size="20" />
<
br />
<?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'];
            
}
            
            
        }?>
<br /><br />
<?php } ?>
<h5>Username</h5>
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

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

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

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


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

<
input type="submit" value="upload" />

</
form>

</
body>
</
html>
 Signature 

Leon Stafford
China Dropship
Twitter Icons

Profile
 
 
Posted: 29 March 2009 09:39 AM   [ Ignore ]   [ # 13 ]  
Grad Student
Rank
Total Posts:  32
Joined  03-24-2009

Please see Single, Multiple and Multiple array upload library for a solution (hopefully soon)...

Profile
 
 
Posted: 12 April 2009 11:36 PM   [ Ignore ]   [ # 14 ]  
Grad Student
Rank
Total Posts:  53
Joined  02-06-2009

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

 Signature 

Leon Stafford
China Dropship
Twitter Icons

Profile
 
 
Posted: 24 April 2009 10:24 AM   [ Ignore ]   [ # 15 ]  
Summer Student
Total Posts:  13
Joined  06-02-2008

The original code not work for me, but here is my simplified working adaptation

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

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

Enjoy and say ‘thaks’ if you find handy wink

Thanks!

Profile
 
 
Posted: 24 April 2009 04:14 PM   [ Ignore ]   [ # 16 ]  
Grad Student
Rank
Total Posts:  32
Joined  03-24-2009

Santiag0, see my post for Single, Multiple and Multiple array upload library…

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

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

Profile
 
 
Posted: 24 April 2009 04:17 PM   [ Ignore ]   [ # 17 ]  
Summer Student
Total Posts:  13
Joined  06-02-2008

Wow, looks great, I will check it out. Thanks a lot Mike!

Profile
 
 
Posted: 24 July 2009 11:58 AM   [ Ignore ]   [ # 18 ]  
Summer Student
Total Posts:  3
Joined  07-24-2009
Leon Stafford - 12 April 2009 11:36 PM

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

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

Thank you

Profile
 
 
Posted: 04 August 2009 10:42 AM   [ Ignore ]   [ # 19 ]  
Summer Student
Total Posts:  11
Joined  02-17-2009

Nice Script, Thanks for Sharing grin

Profile
 
 
Posted: 19 November 2009 01:03 AM   [ Ignore ]   [ # 20 ]  
Summer Student
Avatar
Total Posts:  18
Joined  11-23-2006
Santiag0 - 24 April 2009 10:24 AM

The original code not work for me, but here is my simplified working adaptation

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

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

Enjoy and say ‘thaks’ if you find handy wink

Thanks!

This code works great BUT must be correct the

$imagename = $uploaded['file_name'].'_tn'.$uploaded['file_ext'];

variable because produce duplicate extension (image.jpg_tn.jpg) in the saved image name.

The little fix is:

$imagename = substr($uploaded['file_name'], 0, -4)."_tn".$uploaded['file_ext'];

i search for a better way to do the last code but im very very tired now so… if someone knows is time to share grin

Bye.

 Signature 

Víctor Hugo Hernández
Twitter / nullun
Cali - Colombia

Profile
 
 
   
2 of 3
2
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 11:15 AM
Total Registered Members: 120478 Total Logged-in Users: 19
Total Topics: 126553 Total Anonymous Users: 2
Total Replies: 665404 Total Guests: 291
Total Posts: 791957    
Members ( View Memberlist )