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

[eluser]Latavish[/eluser]
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!! :-) 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

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

Code:
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');

        }
        
        
        
    }
#2

[eluser]webbymonk[/eluser]
Thanks for this code...
I try it but it didn'working or maybe is there something wrong with my view file?

-----------------------------------------------------------------

&lt;form action="http://192.168.1.133/neo/index.php/neomin/picupload" method="post" enctype="multipart/form-data"&gt;
&lt;input type="file" name="key" size="20" /&gt;
&lt;input type="file" name="key2" size="20" /&gt;
&lt;input type="file" name="key3" size="20" /&gt;
&lt;input type="submit" value="upload" /&gt;
&lt;/form&gt;


-----------------------------------------------------------------
#3

[eluser]webbymonk[/eluser]
Thanks lavatish, finally i can make it works...
here is my code

Controller
Code:
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'] = "&lt;link href=\"" .base_url()."css/admin.css\" rel=\"stylesheet\" type=\"text/css\" /&gt;";

        $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

Code:
&lt;input type="text" name="pic_title[]" value="" /&gt;
&lt;textarea name="pic_desc[]"&gt;&lt;/textarea>

&lt;input type="text" name="pic_title[]" value="" /&gt;
&lt;textarea name="pic_desc[]"&gt;&lt;/textarea>

&lt;input type="text" name="pic_title[]" value="" /&gt;
&lt;textarea name="pic_desc[]"&gt;&lt;/textarea>

Thanks...
#4

[eluser]Asinox[/eluser]
Nice code Smile


Thanks
#5

[eluser]Mitja[/eluser]
Hi, very nice tutorial but i have problemm

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

Quote:A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Filename: libraries/Upload.php

Line Number: 152

View is:

<tr><td>Fotka: &lt;input type="file" name="pluspayment_title_photo[]" /&gt;&lt;/tr>

what i am doing wrong?
#6

[eluser]jdgiotta[/eluser]
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?
#7

[eluser]donpepito[/eluser]
[quote author="Mitja" date="1216061134"]Hi, very nice tutorial but i have problem[/quote]


Hi!
Instead of checking this:
Code:
if (!empty($key['name'])) {

try this:
Code:
if (!empty($value['name'])) {

In this case don't use array in file upload fields, add a counter after them:
Code:
&lt;input type="file" name="userfile_1" /&gt;
&lt;input type="file" name="userfile_2" /&gt;
&lt;input type="file" name="userfile_3" /&gt;
#8

[eluser]Xeoncross[/eluser]
[quote author="donpepito" date="1219334838"]
try this:
Code:
if (!empty($value['name'])) {
[/quote]

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

Just switch to boolean:

Code:
if($value['name']) {
#9

[eluser]Rick Jolly[/eluser]
[quote author="Xeoncross" date="1219368396"][quote author="donpepito" date="1219334838"]
try this:
Code:
if (!empty($value['name'])) {
[/quote]

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

Just switch to boolean:

Code:
if($value['name']) {
[/quote]

It's not the same thing. From the php manual:
Quote: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:
Code:
if (! $_POST['does_not_exist']) // undefined index error
While empty() checks isset() first, so no error is produced:
Code:
if (empty($_POST['does_not_exist'])) // no error
#10

[eluser]Xeoncross[/eluser]
[quote author="Rick Jolly" date="1219369891"]
So this produces an undefined index error:
Code:
if (! $_POST['does_not_exist']) // undefined index error
While empty() checks isset() first, so no error is produced:
Code:
if (empty($_POST['does_not_exist'])) // no error
[/quote]

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.




Theme © iAndrew 2016 - Forum software by © MyBB