Part of the EllisLab Network
   
 
upload multiple files to multiple folders
Posted: 23 October 2008 08:35 AM   [ Ignore ]  
Grad Student
Rank
Total Posts:  55
Joined  10-19-2007

i am trying to upload multiple files to multiple folders. For this I am using this code:

function do_upload()
  {
      $files = array(‘userfile1’=>array(‘upload_path’=>’./uploads/file1/’,‘allowed_types’=>‘gif|jpg|png’,‘max_size’=>100), ‘userfile2’=>array(‘upload_path’=>’./uploads/file2/’,‘allowed_types’=>‘gif|jpg|png’,‘max_size’=>100));
     
      $this->load->library(‘upload’);
     
      //Below Line Added By ANUJ
 
      foreach($files as $field=>$settings)
      {
       
        $this->upload->initialize($settings);
        //Above Line Added By ANUJ
        if ( ! $this->upload->do_upload($field))
        {
          $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);
          echo $data[‘upload_data’][‘file_name’];
        }
      }
  }
 
 

      // Multi Files
  function do_upload()
  {
      $config[‘upload_path’] = ‘./uploads/file1/’;
      $config[‘allowed_types’] = ‘gif|jpg|png’;
      $config[‘max_size’] = ‘100’;
     
     
      $this->load->library(‘upload’);
     
     
      foreach($_FILES as $key => $value)
      {
        if( ! empty($key))
        {
     
          $this->upload->initialize($config);
           
          if ( ! $this->upload->do_upload($key))
          {
              print_r($errors[] = $this->upload->display_errors());
          }
          else
          {
           
              //$this->Process_image->process_pic();
           
          }
        }
      }
  }

In 1st code, it comes an error “Unable to find a post variable called userfile.” How to resolve it?
The 2nd code runs fine separately but not when merge with 1st code.

Please suggest how to overcome this problem?

TIA

 Signature 

Meet Me

Profile
 
 
Posted: 23 October 2008 08:38 AM   [ Ignore ]   [ # 1 ]  
Grad Student
Rank
Total Posts:  55
Joined  10-19-2007

Some changes in previous post:

The files are of different types too ie gif|png|jpg   and   avi|swf|fla   and   doc|pdf|txt

 Signature 

Meet Me

Profile
 
 
Posted: 24 October 2008 11:34 AM   [ Ignore ]   [ # 2 ]  
Summer Student
Avatar
Total Posts:  17
Joined  05-08-2008

I’m hoping to find out how to do exactly that. So I’m going to post here in the hopes that someone can come along and rain down a little wisdom on the subject.

I’m hoping to be able to put something like this into a Library or extend the native Uploader controller and put it on the Wiki for all to benefit from. This seems like such a useful tool, but I am also unable to figure out how to solve this from the many posts on this subject.

Good luck! Please let us know if you find a solution!

 Signature 

www.poccuo.com

Profile
 
 
Posted: 24 October 2008 12:32 PM   [ Ignore ]   [ # 3 ]  
Sr. Research Associate
RankRankRankRankRank
Total Posts:  4785
Joined  07-14-2006

Multiple file uploads, even with different file types and directories are not that difficult. The magic method in this scenario is initialize. In pseudo code :

- load library
- initialize
- upload first file
- initialize
- upload second file
- repeat until you run out of memory

a simple function to process files

function multi_upload($configs,$files)
{
    $this
->load->library('upload');

    if(
count($configs) != count($files))
    
{
       
return 'array_count_wrong';
    
}
    
    $errors 
$successes = array(); 

    for(
$i=0$j count($files);$i<$j;$i++)
    
{
       $this
->upload->initialize($config[$[$i]);

       if( ! 
$this->upload->do_upload($files[$i]))
       
{
           $errors[$files[$i]] 
$this->upload->display_errors();
       
}
       
else
       
{
           $successes[$files[$i]] 
$this->upload->data();
       
}
    }

    
return array($errors$successes);
Profile
 
 
Posted: 27 October 2008 11:35 AM   [ Ignore ]   [ # 4 ]  
Summer Student
Avatar
Total Posts:  17
Joined  05-08-2008

This looks really smart. I wonder if you could post some example “in use” code. I just want to be sure that I understand the code entirely.

I really feel like this is a huge step closer to helping me understand how this all works. If you could just help one more step I think that would be it. Thanks for your help.

 Signature 

www.poccuo.com

Profile
 
 
Posted: 27 October 2008 11:51 AM   [ Ignore ]   [ # 5 ]  
Sr. Research Associate
RankRankRankRankRank
Total Posts:  4785
Joined  07-14-2006
// configs
$config[0]['upload_path''./uploads/';
$config[0]['allowed_types''gif|jpg|png';
$config[0]['max_size']    '100';
$config[0]['max_width']  '1024';
$config[0]['max_height']  '768';
// files
$files[] 'userfile';
// upload
$messages $this->library->multi_upload($config,$files);
// check uploads status
if(is_string($messages))
// array_count_wrong message
    
$errors = array($this->lang->line($messages));  
}
else
{
    
list($errors$successes) = $messages;
}
// rest of the code 

If you add the method to the MY_Upload.php extending class you can remove all the upload-> parts and the loading of the library.

Profile
 
 
Posted: 27 October 2008 12:53 PM   [ Ignore ]   [ # 6 ]  
Summer Student
Avatar
Total Posts:  17
Joined  05-08-2008

Okay, I feel at a loss. I tihnk what you’re showing me makes sense but I’m not getting all the right parts speaking to one another. Could you please look at what I’m doing and help explain this?


system/application/libraries/multi_upload.php:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
Multi_upload {

    
function multi_upload($configs,$files){
        $this
->load->library('upload');

        if(
count($configs) != count($files)){
           
return 'array_count_wrong';
        
}

        $errors 
$successes = array();

        for(
$i=0$j count($files);$i<$j;$i++){
           $this
->upload->initialize($config[$i]);

           if( ! 
$this->upload->do_upload($files[$i])){
               $errors[$files[$i]] 
$this->upload->display_errors();
           
else {
               $successes[$files[$i]] 
$this->upload->data();
           
}
        }

        
return array($errors$successes);
    
}
}?> 

system/application/controllers/cms/portfolio.php :

function edit($id FALSE){

        
if($id)//editing an existing post

            
$this->db->select('portfolio.portfolio_id, portfolio.title, portfolio.client, portfolio.content, portfolio.url_image, portfolio.url_video');
            
$this->db->from('portfolio');
            
$this->db->where('portfolio.portfolio_id'$id);
            
$query $this->db->get('portfolio'1);
            
$portfolio $query->row();

            
$data ['portfolio_id']    =     $portfolio->portfolio_id
            
$data ['title']            =     $portfolio->title
            
$data ['client']        =     $portfolio->client
            
$data ['content']        =     $portfolio->content
            
$data ['url_image']        =     $portfolio->url_image;
            
$data ['url_video']        =     $portfolio->url_video;

        
else //creating a new post
            
            
$data ['portfolio_id']    =     "";
            
$data ['title']            =     "";
            
$data ['client']        =     "";
            
$data ['content']        =     ""
            
$data ['url_image']        =     "";
            
$data ['url_video']        =     "";
        
}
        
        
if (count($_POST) > 0){

            $this
->load->library('multi_upload');
            
            
// configs
            
$config[0]['upload_path''./_uploads/images/';
            
$config[0]['allowed_types''gif|jpg|png';
            
$config[0]['max_size']    '1000';
            
$config[0]['max_width']  '50';
            
$config[0]['max_height']  '50';
            
$config[1]['upload_path''./_uploads/flv/';
            
$config[1]['allowed_types''flv';
            
$config[1]['max_size']    '30000';

            
// files
            
$files[0] 'userfile_0';
            
$files[1] 'userfile_1';

            
// upload
            
$messages $this->library->multi_upload($config,$files);

            
// check uploads status
            
if(is_string($messages))// array_count_wrong message
                
$errors = array($this->lang->line($messages));  
            
else {
                
list($errors$successes) = $messages;
            
}
        }
        
        
// rest of the code

        
$this->load->view('cms/crud/portfolio/edit'$data);

    


system/application/cms/portfolio/edit.php (after output) :

<form action="http://localhost:9070/cms/portfolio/edit" method="post" id="edit_form" name="edit_form" enctype="multipart/form-data">    

    <
fieldset>
        <
legend>Create/Edit Portfolio Item</legend>

        <
label>Client </label><br />
        <
input type="text" name="client" class="input_text required" value="" /><br />

        <
label>Title </label><br />
        <
input type="text" name="title" class="input_text required" value="" /><br />

        <
label>Content <span class='instruction' id="character_limit">(Current Characters: <span id="countBody">0</span>/200)</span></label><br />
        <
textarea id="counttxt" name="content" class="input_text required" rows="6" cols="#"></textarea>

        <
label>Image Upload <span class="instruction">(50x50 .gifjpg, or .png only)</span></label><br />
        <
input type="file" name="userfile_0" value="" class="required"  />

        <
label>Video Upload <span class="instruction">(.flv files only)</span></label><br />
        <
input type="file" name="userfile_1" value="" class="required"  />

        <
hr />

        <
input type="submit" name="submit" class="submit" value="Submit" />

    </
fieldset>

</
form

Results in the following output:

A PHP Error was encountered

Severity: Warning

Message: Missing argument 1 for Multi_upload::multi_upload(), called in /Users/kessinger/Sites/xer001_9070/system/libraries/Loader.php on line 873 and defined

Filename: libraries/multi_upload.php

Line Number: 5
A PHP Error was encountered

Severity: Warning

Message: Missing argument 2 for Multi_upload::multi_upload(), called in /Users/kessinger/Sites/xer001_9070/system/libraries/Loader.php on line 873 and defined

Filename: libraries/multi_upload.php

Line Number: 5
A PHP Error was encountered

Severity: Notice

Message: Undefined property: Multi_upload::$load

Filename: libraries/multi_upload.php

Line Number: 6

Fatal error: Call to a member function library() on a non-object in /Users/kessinger/Sites/xer001_9070/system/application/libraries/multi_upload.php on line 6

 Signature 

www.poccuo.com

Profile
 
 
Posted: 27 October 2008 03:37 PM   [ Ignore ]   [ # 7 ]  
Sr. Research Associate
RankRankRankRankRank
Total Posts:  4785
Joined  07-14-2006

If you name the library multi_upload the method should be named differently otherwise php thinks it’s the class constructor method.

// MY_Upload.php
class MY_Upload extends CI_Upload
{
   
function multi_upload($configs,$files)
   
{
    
    
if(count($configs) != count($files))
    
{
       
return 'array_count_wrong';
    
}
    
    $errors 
$successes = array();

    for(
$i=0$j count($files);$i<$j;$i++)
    
{
       $this
->initialize($config[$[$i]);

       if( ! 
$this->do_upload($files[$i]))
       
{
           $errors[$files[$i]] 
$this->display_errors();
       
}
       
else
       
{
           $successes[$files[$i]] 
$this->data();
       
}
    }

    
return array($errors$successes);
  
}

// controller
$this->load->library('upload');

$config[0]['upload_path''./_uploads/images/';
            
$config[0]['allowed_types''gif|jpg|png';
            
$config[0]['max_size']    '1000';
            
$config[0]['max_width']  '50';
            
$config[0]['max_height']  '50';
            
$config[1]['upload_path''./_uploads/flv/';
            
$config[1]['allowed_types''flv';
            
$config[1]['max_size']    '30000';

            
// files
            
$files[0] 'userfile_0';
            
$files[1] 'userfile_1';

            
// upload
            
$messages $this->upload->multi_upload($config,$files); 

That should do the trick.

Profile
 
 
Posted: 06 November 2008 05:49 PM   [ Ignore ]   [ # 8 ]  
Grad Student
Rank
Total Posts:  72
Joined  01-02-2008

Here is an error, I fix it. Works good.

$this->initialize($config[$[$i]); 

to

$this->initialize($configs[$i]); 

This is excellent, the problem is, if an error happen, you need to re-upload all the files again, I’m trying to fix this but its really hard.

Profile
 
 
Posted: 03 December 2008 10:23 AM   [ Ignore ]   [ # 9 ]  
Summer Student
Total Posts:  8
Joined  09-23-2008

I have a problem with this…
So i got:

<?
//MY_Upload.php
class MY_Upload extends CI_Upload
{
   
function multi_upload($configs,$files)
   
{
    
    
if(count($configs) != count($files))
    
{
       
return 'array_count_wrong';
    
}
    
    $errors 
$successes = array();

    for(
$i=1$j count($files);$i<$j;$i++)
    
{
       $this
->initialize($configs[$i]);

       if( ! 
$this->do_upload($files[$i]))
       
{
           $errors[$files[$i]] 
$this->display_errors();
       
}
       
else
       
{
           $successes[$files[$i]] 
$this->data();
       
}
    }

    
return array($errors$successes);
  
}
}
?> 

And my controller:

function add_set() {
        $pics_count 
$this->input->post('pics_count');
        
$this->load->library('upload');
        
        for(
$x=1$x<=$pics_count$x++){
            $config[$x][
'upload_path'realpath('application/views/photos/albums/');
            
$config[$x]['allowed_types''gif|jpg|png';
            
$config[$x]['max_size']    '1000';
            
$config[$x]['max_width']  '1024';
            
$config[$x]['max_height']  '768';

            
// files
            
$files[$x] 'pic'.$x;
            
// upload
            
$messages $this->upload->multi_upload($config,$files); 
            
            if(
is_string($messages))
            
// array_count_wrong message
                
$errors = array($this->lang->line($messages));  
            
}
            
else
            
{
                
list($errors$successes) = $messages;
            
}
        } 

And my view:

<?=form_open_multipart('admin/admin_albums/add_set')?>
    
<table cellpadding="0" cellspacing="0">
        <
tr>
            <
td>Pics:</td>
            <
td>
                <
input type="button" name="button" id="button" value="Add pic" on+click="addpic()" />
                <
div id="pics"></div>
                <
input type="hidden" name="pics_count" id="pics_count" value="0">
            </
td>
        </
tr>
        <
tr>
            <
td colspan="2">
                <
input type="submit" value="Add album">
            </
td>
        </
tr>
    </
table>
    </
form

The problem is with 3 or more files. If I upload 2 files everything wroks just fine but when i try to upload 3 or more it keeps repeating the first two.

Example:
file1 = picA.jpg;
file2 = picB.jpg;
file3 = picC.jpg;

The script will upload: picA.jpg, picB.jpg and picA1.jpg.

Thanks in advance.

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

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

Profile