Upload Multiple Codeigniter

Asked

Viewed 1,084 times

3

I have a form for multiple image uploads using codeigniter:

<input type="file" name="files[]" id="filer_input2" multiple>

And PHP:

#configuracoes base
$config['upload_path'] = $diretorio;
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf';
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$config['max_size'] = '8192'; // 8Mbs


#inicia a biblioteca
$this->load->library('upload', $config);
$this->upload->initialize($config);


foreach($_FILES['files']['name'] as $valor){
    echo $valor."<br>"; 
}

But when trying to upload, it does not accept if there are several, it has to be one by one. As I upload multiple in codeigniter?

  • Natively the class file Just one file, business is to use $_FILES in your case you missed the Dice and use a.

  • I don’t understand, the normal class only uploads.. but what suggests me to upload?

  • There’s this one lib that uploads multiple files based on the CI class, I have never used.

  • I posted a solution, I use it in my systems.

  • Okay, but how do I include her in the library?

  • Create a new file called files within the Libraries directory, paste the code, and use it as described.

Show 1 more comment

2 answers

2


Friend, I have a class for this purpose. Create a library in your project and add the class code.

class Files {

    private $Files        =   null;

    private $SaveTo       =   null;

    private $Length       =   null;        

    private $Response     =   array();

    private $Extensions   =   array();

    public function __construct( $files = '' ){

        $this->Files   =   $files;

    }


    public function setFile( $file ) {

        $this->Files   =   $file;

    }


    public function initialize( $dirToSave, $length, $fileExtension = array() ) {

        $this->SaveTo      =  $dirToSave;

        $this->Length      =  $length;

        $this->Extensions  =  $fileExtension;

    }

    public function processMultFiles() {

        if( is_dir( $this->SaveTo ) ) {

            $countFiles   =   count( $this->Files['name'] );

            if( $countFiles > 0 ) {

                for ($i = 0; $i < $countFiles; $i++ ) { 

                    if( isset( $this->Files['name'][$i] ) && trim( $this->Files['name'][$i] ) != '' ) {

                        $extensao  =  strtolower( end( explode( '.', $this->Files['name'][$i] ) ) );

                        $length    =  $this->Files['size'][$i];

                        $name      =  $this->Files['name'][$i];

                        if( array_search($extensao, $this->Extensions ) === false ) {

                            $this->Response['status']   =   $name . ' - Arquivo não permitido';

                            $this->Response['code']     =   102;

                            break;

                        }else if( $length > $this->Length ) {

                            $this->Response['status']   =   $name . ' - Arquivo excede o limite de tamanho de: ' . $this->Length . ' KB';

                            $this->Response['code']     =   102;

                            break;

                        }

                    }

                }

                if( !isset( $this->Response['code'] ) ) {

                    for ($i = 0; $i < $countFiles; $i++ ) {

                        if( isset( $this->Files['name'][$i] ) && trim( $this->Files['name'][$i] ) != '' ) {

                            if( !isset( $this->Response['code'] ) ) {

                                $cond  =  false;

                                $name  =  $this->Files['name'][$i];

                                while( !$cond ) {

                                    $name    =   rand(000000000, 9999999999) . '.' . $extensao;

                                    $file    =   $this->SaveTo . $name;

                                    if( !file_exists( $file ) ) {

                                        $cond  =  true;

                                    }

                                }

                                if( move_uploaded_file( $this->Files['tmp_name'][$i], $file ) ) {

                                    $this->Response[$i]['status']  =  100;

                                    $this->Response[$i]['file']    =  $file;

                                }else {

                                    $this->Response['status']   =   $name . ' - Ocorreu um erro ao tentar salvar o arquivo';

                                    $this->Response['code']     =   102;

                                    $this->deleteFileProcessed( $this->Response );

                                    break;

                                }

                            }

                        }

                    }

                }

                return $this->Response;

            }

        }else {

            $this->Response['status']   =   'Ocorreu um erro inesperado';

            $this->Response['code']     =   102;

        }

        return $this->Response;

    }


    public function processSingleFile() {

        if( is_dir( $this->SaveTo ) ) {



            $countFiles   =   count( $this->Files['name'] );



            if( $countFiles > 0 ) {

                if( isset( $this->Files['name'] ) && trim( $this->Files['name'] ) != '' ) {

                    $extensao  =  strtolower( end( explode( '.', $this->Files['name'] ) ) );

                    $length    =  $this->Files['size']; 

                    $name      =  $this->Files['name']; 



                    if( array_search($extensao, $this->Extensions ) === false ) {

                        $this->Response['status']   =   $extensao . ' - Arquivo não permitido';

                        $this->Response['code']     =   102;



                    }else if( $length > $this->Length ) {

                        $this->Response['status']   =   $name . ' - Arquivo excede o limite de tamanho de: ' . $this->Length . ' KB';

                        $this->Response['code']     =   102;



                    }

                }


                if( !isset( $this->Response['code'] ) ) {




                        if( isset( $this->Files['name'] ) && trim( $this->Files['name'] ) != '' ) {


                            if( !isset( $this->Response['code'] ) ) {

                                $cond  =  false;

                                $name  =  $this->Files['name'];

                                while( !$cond ) {

                                    $name    =   rand(000000000, 9999999999) . '.' . $extensao;

                                    $file    =   $this->SaveTo . $name;

                                    if( !file_exists( $file ) ) {

                                        $cond  =  true;

                                    }

                                }



                                if( move_uploaded_file( $this->Files['tmp_name'], $file ) ) {

                                    $this->Response['status']  =  100;

                                    $this->Response['file']    =  $file;

                                }else {

                                    $this->Response['status']   =   $file . ' - Ocorreu um erro ao tentar salvar o arquivo';

                                    $this->Response['code']     =   102;


                                }

                            }

                        }


                }

                return $this->Response;

            }

        }else {

            $this->Response['status']   =   'Ocorreu um erro inesperado';

            $this->Response['code']     =   102;

        }

        return $this->Response;

    }

    public function deleteFileProcessed( $files ) {

        for( $i = 0; $i < count( $files ); $i++ ) {

            $file  =  $files[$i]['file'];

            @unlink( $file );

        }

    }


}

For use:

    //Instancia a classe de arquivos
    $this->load->library( 'files' );

    //Diretório onde a imagem será gravada temporariamente
    $dirToSave      =   'assets/img/upload/logo_empresa/';

    //Limite do tamanho máximo que a imagem deve ter
    $length         =   1048576; //1 MB por arquivo

    //Extensões permitidas para os arquivos
    $fileExtension  =   array( 'jpg', 'jpeg', 'png' );

    //Inicializa os parametros necessários para upload da imagem
    $this->files->initialize( $dirToSave, $length, $fileExtension );

    //Verifica se alguma imagem foi selecionada
    $image         =   isset( $_FILES[ 'image' ] ) ? $_FILES[ 'image' ] : null;
    if( !is_null( $image ) ) {

        //Seta o arquivo para upload
        $this->files->setFile( $image );

        //Processa o arquivo e recebe o retorno
        $upload  =   $this->files->processMultFiles();

        //Verifica retornbou algum código, se sim, ocorreu algum erro no upload
        isset( $upload['code'] ) ? 'mensagem de erro' : null;

        //Retorna o diretorio onde os arquivos foram salvos
        print_r( $upload );

    }
  • 1

    Reminder: Give write permission in the directory where images will be saved.

  • Message: Undefined Property: CI::$Files this error appears, as much as I have included the confrere file you said.

  • You are wrong, in this line : $this->Files->initialize( $dirToSave, $length, $fileExtension ), change to $this->files->initialize( $dirToSave, $length, $fileExtension ).

  • Returned the data in print_r, but did not send the image to the server... I checked the folder, it is correct!

  • It worked out, brother, thanks anyway!

  • What directory you passed in the parameter and what is your directory structure, where your codeigniter project is ?

  • Remember that the upload is based on your root directory, i.e., var/www/codeigniter. If you place Assets/image, the Assets, needs to be inside the codeigniter directory.

  • It was nothing, buddy. Enjoy.

Show 3 more comments

1

The standard CI upload class does not allow sending multiple files, an alternative is this library and another is to use the $_FILES even.

$total = count($_FILES['files']['name']);

for($i=0; $i<$total;$i++){
   if(!move_uploaded_file($_FILES['files']['tmp_name'][$i], 'arquivos/novo_nome.jpg')){
      echo 'arquivo não importado';
   }
}

Remember to make a deal if you cannot upload.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.