Part of the EllisLab Network
   
1 of 3
1
Latavish’s Multiple Image Upload with Thumbnail Generation
Posted: 27 May 2008 07:41 AM   [ Ignore ]  
Summer Student
Avatar
Total Posts:  24
Joined  03-27-2008

Latavish’s Multiple Image Upload w/ Thumbnail Generation

Hi CI lovers,
I hope you guys had a GREAT and EXTENDED weekend. Been working on this for a few days now and finally finished up this weekend and wanted to share my work with this great community. Now this code is really customizable so feel free to trick it out to fit your needs. Code may not be perfect because I designed this to fit my needs on a project that i’m doing. (a nice CMS) If you find this code useful all I require is a simple thanks! TeeHee!! grin Happy Coding…

Features:
Upload Multiple Images at once
Automatically Renames Images to a random name (protects file from being overwritten)
Adds Image Information to DB

C O N T R O L L E R

class Upload extends Controller {

    
function Upload()
    
{
        parent
::Controller();
        
$this->load->helper(array('form','url','file'));
        
    
    
}
    
    
function index()
    
{
        
        $this
->load->view('upload/upload_index'); //Upload Form
        
    
}

    
function picupload()
    
{
        
//Load Model
        
$this->load->model('Process_image');

        
$config['upload_path'] = './uploads/';
        
$config['allowed_types'] = 'gif|jpg|png';
        
$config['max_size']    = '2048'; //2 meg


        
$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();
                    
                
}    
                
else
                
{

                    $this
->Process_image->process_pic();

                
}
             }
        
        }
        
        
        $data[
'success'] = 'Thank You, Files Upladed!';

        
$this->load->view('upload/upload_pictures', $data); //Picture Upload View

        
        
        
    
}

M O D E L

class Process_image extends Model {
    
    
function Process_image()
    
{
        parent
::Model();
        
        
$this->load->library('image_lib');
        
//Generate random Activation code
        
        
function generate_code($length = 10){
    
                
if ($length <= 0)
                
{
                    
return false;
                
}
            
                $code
= "";
                
$chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                
srand((double)microtime() * 1000000);
                for (
$i = 0; $i < $length; $i++)
                
{
                    $code
= $code . substr($chars, rand() % strlen($chars), 1);
                
}
                
return $code;
            
                
}

    }

function process_pic()
    
{   
        
//Connect to database
        
$this->load->database();
        
        
//Get File Data Info
        
$uploads = array($this->upload->data());
        
        
$this->load->library('image_lib');

        
//Move Files To User Folder
        
foreach($uploads as $key[] => $value)
        
{
            
                        
//Gen Random code for new file name
            
$randomcode = generate_code(12);
            
            
$newimagename = $randomcode.$value['file_ext'];
            
            
//Creat Thumbnail
            
$config['image_library'] = 'GD2';
            
$config['source_image'] = $value['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;
            
$config['new_image'] = '/pictures/'.$newimagename;

            
//$this->image_lib->clear();
            
$this->image_lib->initialize($config);
            
//$this->load->library('image_lib', $config);
            
$this->image_lib->resize();
            
            
//Move Uploaded Files with NEW Random name
            
rename($value['full_path'],'/pictures/'.$newimagename);
            
            
//Make Some Variables for Database
            
$imagename = $newimagename;
            
$thumbnail = $randomcode.'_tn'.$value['file_ext'];
            
$filesize = $value['file_size'];
            
$width = $value['image_width'];
            
$height = $value['image_height'];
            
$timestamp = time();
            
            
//Add Pic Info To Database
            
$this->db->set('imagename', $imagename);
            
$this->db->set('thumbnail', $thumbnail);
            
$this->db->set('filesize', $filesize);
            
$this->db->set('width', $width);
            
$this->db->set('height', $height);
            
$this->db->set('timestamp', $timestamp);
            
            
//Insert Info Into Database
            
$this->db->insert('pictures');

        
}
        
        
        
    }
 Signature 

———————————
Programming Is an Art

Profile
 
 
Posted: 09 June 2008 11:28 PM   [ Ignore ]   [ # 1 ]  
Summer Student
Total Posts:  21
Joined  05-05-2008

Thanks for this code…
I try it but it didn’working or maybe is there something wrong with my view file?

————————————————————————————————-

<form action=“http://192.168.1.133/neo/index.php/neomin/picupload” method=“post” enctype=“multipart/form-data”>
  <input type=“file” name=“key” size=“20” />
  <input type=“file” name=“key2” size=“20” />
  <input type=“file” name=“key3” size=“20” />
  <input type=“submit” value=“upload” />
</form>


————————————————————————————————-

Profile
 
 
Posted: 11 July 2008 11:58 PM   [ Ignore ]   [ # 2 ]  
Summer Student
Total Posts:  21
Joined  05-05-2008

Thanks lavatish, finally i can make it works…
here is my code

Controller

function upload_tour_pic() {
        $this
->load->helper(array('form','url','file'));
        
$data['title'] = "Upload Pictures";
        
$data['query'] = $this->tour_model->get_tour();
        
$this->load->view('upload_tour_pic', $data);
}
     
function picupload()
{
        
//Load Model
        
$this->load->helper(array('form','url','file'));
        
$this->load->model('Process_image');
        
$this->load->model('tourpic_model');
        
$this->load->library('upload');
        
$this->load->library('validation');
        
        
$gmt=false;
        
$time = ($gmt)  ? gmstrftime("%Y-%m-%d %H:%M:%S", time()) : strftime("%Y-%m-%d %H:%M:%S", time());
        
    
        
        
$picInfo = array(
                
'tour_id' => (int) $this->input->post('tour_id'),
                
'timestamp' => $time
        
);

        
        
$config['upload_path'] = './uploads/';
        
$config['allowed_types'] = 'gif|jpg|png';
        
$config['max_size']    = '8048'; //2 meg

        
        
$data['extraHead'] = "<link href=\"" .base_url()."css/admin.css\" rel=\"stylesheet\" type=\"text/css\" />";

        
$i=1;
        
$j=1;
        foreach(
$_FILES as $key => $value)
        
{
            
if( ! empty($key['name']))
            
{
                $this
->upload->initialize($config);
                
$data['title'] = 'Files Upload!';
                if ( !
$this->upload->do_upload($key))
                
{
                    $data[
'error'][$j] =  $this->upload->display_errors();    
                    
$j++;
                
}    
                
else
                
{
                    $this
->Process_image->process_pic($picInfo);
                    
$data['success'] = 'Thank You, Files Upladed!';
                    
$data['upload_data'][$i]  = $this->upload->data();
                    
$i++;
                
}
            }
        }
        
        
        
            $data[
'query'] = $this->tour_model->get_tour();
            
$data['rowpic'] = $this->tourpic_model->get_pic_code($picInfo);
            
$data['countdata'] = count($data['upload_data']);
            
$data['counterr'] = count($data['error']);
            
            
//$data['query'] = $this->tourpic_model->get_pic_code($picInfo);
            
$this->load->view('upload', $data);
            
            
            
    
}

now I think i want to add some fields for the image, like title and description…
Do anyone have idea how to loop array of fields and insert it into database..
For example:
image1 - title1 - desc1
image2 - title2 - desc2
image3 - title3 - desc3

<input type="text" name="pic_title[]" value="" />
<
textarea name="pic_desc[]"></textarea>

<
input type="text" name="pic_title[]" value="" />
<
textarea name="pic_desc[]"></textarea>

<
input type="text" name="pic_title[]" value="" />
<
textarea name="pic_desc[]"></textarea>

Thanks…

Profile
 
 
Posted: 12 July 2008 04:25 PM   [ Ignore ]   [ # 3 ]  
Lab Assistant
RankRank
Total Posts:  225
Joined  06-04-2007

Nice code smile


Thanks

 Signature 

http://www.asinox.net
CodeIgniter code and more.

Profile
 
 
Posted: 14 July 2008 07:45 AM   [ Ignore ]   [ # 4 ]  
Grad Student
Rank
Total Posts:  43
Joined  05-27-2008

Hi, very nice tutorial but i have problemm

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

if ( !$this->upload->do_upload($key)) show me an error of

A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Filename: libraries/Upload.php

Line Number: 152

View is:

<tr><td>Fotka: <input type=“file” name=“pluspayment_title_photo[]” /></tr>

what i am doing wrong?

Profile
 
 
Posted: 08 August 2008 04:18 PM   [ Ignore ]   [ # 5 ]  
Summer Student
Avatar
Total Posts:  15
Joined  02-26-2008

I’m using your example in my application, but every once in a while the files get confused.
The user choose 3 files for 3 different purposes and each are moved to their own respective folder. Yet, for some reason files become mismatched intermittently.


Has anyone experienced this?

Profile
 
 
Posted: 21 August 2008 05:07 AM   [ Ignore ]   [ # 6 ]  
Summer Student
Avatar
Total Posts:  3
Joined  12-14-2007
Mitja - 14 July 2008 07:45 AM

Hi, very nice tutorial but i have problem


Hi!
Instead of checking this:

if (!empty($key['name'])) {

try this:

if (!empty($value['name'])) {

In this case don’t use array in file upload fields, add a counter after them:

<input type="file" name="userfile_1" />
<
input type="file" name="userfile_2" />
<
input type="file" name="userfile_3" />
Profile
 
 
Posted: 21 August 2008 02:26 PM   [ Ignore ]   [ # 7 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  491
Joined  07-16-2008
donpepito - 21 August 2008 05:07 AM

try this:

if (!empty($value['name'])) {

Why do people even waste CPU time on the empty function?

Just switch to boolean:

if($value['name']) {
 Signature 

My Blog, C2D, PHP Videos, CXTags, Super .htaccess, Extra hooks, and MicroMVC

Profile
 
 
Posted: 21 August 2008 02:51 PM   [ Ignore ]   [ # 8 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  837
Joined  02-05-2007
Xeoncross - 21 August 2008 02:26 PM
donpepito - 21 August 2008 05:07 AM

try this:

if (!empty($value['name'])) {

Why do people even waste CPU time on the empty function?

Just switch to boolean:

if($value['name']) {

It’s not the same thing. From the php manual:

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

So this produces an undefined index error:

if (! $_POST['does_not_exist']) // undefined index error

While empty() checks isset() first, so no error is produced:

if (empty($_POST['does_not_exist'])) // no error
 Signature 

“I am the terror that flaps in the night”

Profile
 
 
Posted: 21 August 2008 03:01 PM   [ Ignore ]   [ # 9 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  491
Joined  07-16-2008
Rick Jolly - 21 August 2008 02:51 PM

So this produces an undefined index error:

if (! $_POST['does_not_exist']) // undefined index error

While empty() checks isset() first, so no error is produced:

if (empty($_POST['does_not_exist'])) // no error

I was assuming you were using a set variable as it is bad practice to just “assume” one is set/unset. But that is right.

 Signature 

My Blog, C2D, PHP Videos, CXTags, Super .htaccess, Extra hooks, and MicroMVC

Profile
 
 
Posted: 06 February 2009 10:37 PM   [ Ignore ]   [ # 10 ]  
Grad Student
Rank
Total Posts:  53
Joined  02-06-2009

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:

<?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:

<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 />
<
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>

Here is my upload_success.php file:

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

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

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

<?
echo img('uploads/'.$upload_data['file_name']);?>

<?
endif;?>

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

</
body>
</
html>
 Signature 

Leon Stafford
China Dropship
Twitter Icons

Profile
 
 
   
1 of 3
1
 
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 721, on January 06, 2010 09:38 AM
Total Registered Members: 114994 Total Logged-in Users: 70
Total Topics: 122435 Total Anonymous Users: 2
Total Replies: 647291 Total Guests: 506
Total Posts: 769726    
Members ( View Memberlist )