Upload Multiplo CodeIgniter

3

I have a form to upload multiple images 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 it is multiple, it has to be one by one. How do I upload multiple in codeigniter?

    
asked by anonymous 27.04.2016 / 15:46

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

        }

    }


}

To 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 );

    }
    
27.04.2016 / 15:59
1

The default CI upload class does not allow multiple files to be uploaded, an alternative is library and another is use $_FILES same.

$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 can not upload.

    
27.04.2016 / 16:05