Carga de archivos múltiples (Array) con CodeIgniter 2.0

He estado buscando y luchando durante 3 días para hacer que esto funcione, pero simplemente no puedo. Lo que quiero hacer es usar un formulario de entrada de varios archivos y luego subirlos. No puedo usar una cantidad fija de archivos para cargar. Intenté muchas soluciones en StackOverflow, pero no pude encontrar una que funcionara.

Aquí está mi controlador de carga

load->helper(array('form', 'url','html')); } function index() { $this->load->view('pages/uploadform', array('error' => ' ' )); } function do_upload() { $config['upload_path'] = './Images/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload'); foreach($_FILES['userfile'] as $key => $value) { if( ! empty($key['name'])) { $this->upload->initialize($config); if ( ! $this->upload->do_upload($key)) { $error['error'] = $this->upload->display_errors(); $this->load->view('pages/uploadform', $error); } else { $data[$key] = array('upload_data' => $this->upload->data()); $this->load->view('pages/uploadsuccess', $data[$key]); } } } } } ?> 

Mi formulario de carga es This.

    Upload Form      

Sigo teniendo este error:

No seleccionó un archivo para cargar.

Aquí está la matriz del ejemplo:

Array ([userfile] => Array ([name] => Array ([0] => youtube.png [1] => zergling.jpg) [type] => Array ([0] => image / png [1 ] => image / jpeg) [tmp_name] => Array ([0] => E: \ wamp \ tmp \ php7AC2.tmp [1] => E: \ wamp \ tmp \ php7AC3.tmp) [error] => Matriz ([0] => 0 [1] => 0) [tamaño] => Matriz ([0] => 35266 [1] => 186448)))

Tengo esto como 5 veces seguidas si selecciono 2 archivos. También uso la biblioteca de carga estándar.

¡Finalmente logré que funcione con tu ayuda!

Aquí está mi código:

  function do_upload() { $this->load->library('upload'); $files = $_FILES; $cpt = count($_FILES['userfile']['name']); for($i=0; $i< $cpt; $i++) { $_FILES['userfile']['name']= $files['userfile']['name'][$i]; $_FILES['userfile']['type']= $files['userfile']['type'][$i]; $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i]; $_FILES['userfile']['error']= $files['userfile']['error'][$i]; $_FILES['userfile']['size']= $files['userfile']['size'][$i]; $this->upload->initialize($this->set_upload_options()); $this->upload->do_upload(); } } private function set_upload_options() { //upload an image options $config = array(); $config['upload_path'] = './Images/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '0'; $config['overwrite'] = FALSE; return $config; } 

¡Gracias chicos!

Debe usar esta biblioteca para carga múltiple en CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload

Instalación Simplemente copie el archivo MY_Upload.php en el directorio de su biblioteca de aplicaciones.

Uso: función test_up en el controlador

 public function test_up(){ if($this->input->post('submit')){ $path = './public/test_upload/'; $this->load->library('upload'); $this->upload->initialize(array( "upload_path"=>$path, "allowed_types"=>"*" )); if($this->upload->do_multi_upload("myfile")){ echo '
'; print_r($this->upload->get_multi_upload_data()); echo '

'; } }else{ $this->load->view('test/upload_view'); }

}

upload_view.php en la carpeta de aplicaciones / vista / prueba

 

Prueba este código

Esta trabajando bien para mi

Debe inicializar cada vez que la biblioteca

  function do_upload() { foreach ($_FILES as $index => $value) { if ($value['name'] != '') { $this->load->library('upload'); $this->upload->initialize($this->set_upload_options()); //upload the image if ( ! $this->upload->do_upload($index)) { $error['upload_error'] = $this->upload->display_errors("", ""); //load the view and the layout $this->load->view('pages/uploadform', $error); return FALSE; } else { $data[$key] = array('upload_data' => $this->upload->data()); $this->load->view('pages/uploadsuccess', $data[$key]); } } } } private function set_upload_options() { //upload an image options $config = array(); $config['upload_path'] = 'your upload path'; $config['allowed_types'] = 'gif|jpg|png'; return $config; } 

Editar más

He encontrado la forma en que debe cargar sus archivos con un cuadro de entrada único

CodeIgniter no es compatible con varios archivos. Usar do_upload () en un foreach no será diferente de usarlo afuera.

Tendrá que lidiar con esto sin la ayuda de CodeIgniter. Aquí hay un ejemplo de https://github.com/woxxy/FoOlSlide/blob/master/application/controllers/admin/series.php#L331-370

https://stackoverflow.com/a/9846065/1171049

Esto es lo que dijo en los comentarios 🙂

otro bit de código aquí:

consulte: https://github.com/stvnthomas/CodeIgniter-Multi-Upload

Como Carlos Rincones sugirió; no tengas miedo de jugar con superglobales.

 $files = $_FILES; for($i=0; $i$v ) { $_FILES['userfile'][$k] = $v[$i]; } $this->upload->do_upload('userfile') } 
  public function imageupload() { $count = count($_FILES['userfile']['size']); $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png|bmp'; $config['max_size'] = '0'; $config['max_width'] = '0'; $config['max_height'] = '0'; $config['image_library'] = 'gd2'; $config['create_thumb'] = TRUE; $config['maintain_ratio'] = FALSE; $config['width'] = 50; $config['height'] = 50; foreach($_FILES as $key=>$value) { for($s=0; $s< =$count-1; $s++) { $_FILES['userfile']['name']=$value['name'][$s]; $_FILES['userfile']['type'] = $value['type'][$s]; $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; $_FILES['userfile']['error'] = $value['error'][$s]; $_FILES['userfile']['size'] = $value['size'][$s]; $this->load->library('upload', $config); if ($this->upload->do_upload('userfile')) { $data['userfile'][$i] = $this->upload->data(); $full_path = $data['userfile']['full_path']; $config['source_image'] = $full_path; $config['new_image'] = './uploads/resiezedImage'; $this->load->library('image_lib', $config); $this->image_lib->resize(); $this->image_lib->clear(); } else { $data['upload_errors'][$i] = $this->upload->display_errors(); } } } } 

He usado el código a continuación en mi biblioteca personalizada
llamarlo desde mi controlador como a continuación,

 function __construct() {
    parent::__construct();
    $this->load->library('CommonMethods');
}
$config = array();
$config['upload_path'] = 'assets/upload/images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_width'] = 150;
$config['max_height'] = 150;
$config['encrypt_name'] = TRUE;
$config['overwrite'] = FALSE;
// upload multiplefiles
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);

 /** * do_upload_multiple_files - Multiple Methods * @param type $fieldName * @param type $options * @return type */ public function do_upload_multiple_files($fieldName, $options) { $response = array(); $files = $_FILES; $cpt = count($_FILES[$fieldName]['name']); for($i=0; $i< $cpt; $i++) { $_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i]; $_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i]; $_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i]; $_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i]; $_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i]; $this->CI->load->library('upload'); $this->CI->upload->initialize($options); //upload the image if (!$this->CI->upload->do_upload($fieldName)) { $response['erros'][] = $this->CI->upload->display_errors(); } else { $response['result'][] = $this->CI->upload->data(); } } return $response; } 
 

MODELO: FilesUpload

 class FilesUpload extends CI_Model { public function setFiles() { $name_array = array(); $count = count($_FILES['userfile']['size']); foreach ($_FILES as $key => $value) for ($s = 0; $s < = $count - 1; $s++) { $_FILES['userfile']['name'] = $value['name'][$s]; $_FILES['userfile']['type'] = $value['type'][$s]; $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; $_FILES['userfile']['error'] = $value['error'][$s]; $_FILES['userfile']['size'] = $value['size'][$s]; $config['upload_path'] = 'assets/product/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '10000000'; $config['max_width'] = '51024'; $config['max_height'] = '5768'; $this->load->library('upload', $config); if (!$this->upload->do_upload()) { $data_error = array('msg' => $this->upload->display_errors()); var_dump($data_error); } else { $data = $this->upload->data(); } $name_array[] = $data['file_name']; } $names = implode(',', $name_array); return $names; } } 

CONTROLADOR enviar

 class Submit extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper(array('html', 'url')); } public function index() { $this->load->model('FilesUpload'); $data = $this->FilesUpload->setFiles(); echo '
'; print_r($data); } }

  // Change $_FILES to new vars and loop them foreach($_FILES['files'] as $key=>$val) { $i = 1; foreach($val as $v) { $field_name = "file_".$i; $_FILES[$field_name][$key] = $v; $i++; } } // Unset the useless one ;) unset($_FILES['files']); // Put each errors and upload data to an array $error = array(); $success = array(); // main action to upload each file foreach($_FILES as $field_name => $file) { if ( ! $this->upload->do_upload($field_name)) { echo ' failed '; }else{ echo ' success '; } } 

Todos los archivos publicados vendrán en la variable $ _FILES, para usar la biblioteca de carga codeigniter necesitamos dar el nombre de campo que estamos usando para cargar (de manera predeterminada será ‘archivo de usuario’), de esta manera obtenemos todo el archivo publicado y creamos otro conjunto de archivos que crean nuestro propio nombre para cada archivo y le dan este nombre a la función do_upload de la biblioteca codeigniter.

 if(!empty($_FILES)){ $j = 1; foreach($_FILES as $filekey=>$fileattachments){ foreach($fileattachments as $key=>$val){ if(is_array($val)){ $i = 1; foreach($val as $v){ $field_name = "multiple_".$filekey."_".$i; $_FILES[$field_name][$key] = $v; $i++; } }else{ $field_name = "single_".$filekey."_".$j; $_FILES[$field_name] = $fileattachments; $j++; break; } } // Unset the useless one unset($_FILES[$filekey]); } foreach($_FILES as $field_name => $file){ if(isset($file['error']) && $file['error']==0){ $config['upload_path'] = [upload_path]; $config['allowed_types'] = [allowed_types]; $config['max_size'] = 100; $config['max_width'] = 1024; $config['max_height'] = 768; $this->load->library('upload', $config); $this->upload->initialize($config); if ( ! $this->upload->do_upload($field_name)){ $error = array('error' => $this->upload->display_errors()); echo "Error Message : ". $error['error']; }else{ $data = $this->upload->data(); echo "Uploaded FileName : ".$data['file_name']; // Code for insert into database } } } } 
 function UploadHotelImage(){ $data = array(); if($this->input->post('fileSubmit') && !empty($_FILES['userFiles']['name'])){ $filesCount = count($_FILES['userFiles']['name']); for($i = 0; $i < $filesCount; $i++){ $_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i]; $_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i]; $_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i]; $_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i]; $_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i]; $uploadPath = 'uploads/files/'; $config['upload_path'] = $uploadPath; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config); $this->upload->initialize($config); if($this->upload->do_upload('userFile')){ $fileData = $this->upload->data(); $uploadData[$i]['file_name'] = $fileData['file_name']; $uploadData[$i]['created'] = date("Ymd H:i:s"); $uploadData[$i]['modified'] = date("Ymd H:i:s"); } } if(!empty($uploadData)){ //Insert file information into the database $insert = $this->file->insert($uploadData); $statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.'; $this->session->set_flashdata('statusMsg',$statusMsg); } } //Get files data from database $data['files'] = $this->file->getRows(); //Pass the files data to view $this->load->view('upload_files/index', $data); } } //----- Model-----------// public function insertHotelImage($data = array()){ $insert = $this->db->insert_batch('tbl_hotel_images',$data); return $insert?true:false; } 

Utilice este código para cargar imágenes múltiples en CI ….

 function imageUpload(){ if ($this->input->post('submitImg') && !empty($_FILES['files']['name'])) { $filesCount = count($_FILES['files']['name']); $userID = $this->session->userdata('userID'); $this->load->library('upload'); $config['upload_path'] = './userdp/'; $config['allowed_types'] = 'jpg|png|jpeg'; $config['max_size'] = '9184928'; $config['max_width'] = '5000'; $config['max_height'] = '5000'; $files = $_FILES; $cpt = count($_FILES['files']['name']); for($i = 0 ; $i < $cpt ; $i++){ $_FILES['files']['name']= $files['files']['name'][$i]; $_FILES['files']['type']= $files['files']['type'][$i]; $_FILES['files']['tmp_name']= $files['files']['tmp_name'][$i]; $_FILES['files']['error']= $files['files']['error'][$i]; $_FILES['files']['size']= $files['files']['size'][$i]; $imageName = 'image_'.$userID.'_'.rand().'.png'; $config['file_name'] = $imageName; $this->upload->initialize($config); if($this->upload->do_upload('files')){ $fileData = $this->upload->data(); //it return $uploadData[$i]['picturePath'] = $fileData['file_name']; } } if (!empty($uploadData)) { $imgInsert = $this->insert_model->insertImg($uploadData); $statusMsg = $imgInsert?'Files uploaded successfully.':'Some problem occurred, please try again.'; $this->session->set_flashdata('statusMsg',$statusMsg); redirect('home/user_dash'); } } else{ redirect('home/user_dash'); } } 

No hay un método predefinido disponible en codeigniter para cargar múltiples archivos al mismo tiempo, pero puede enviar archivos en una matriz y cargarlos uno por uno

aquí está la referencia: aquí está la mejor opción para subir varios archivos en codeigniter 3.0.1 con vista previa https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/

Recientemente trabajé en eso. Prueba esta función:

 /** * @return array an array of your files uploaded. */ private function _upload_files($field='userfile'){ $files = array(); foreach( $_FILES[$field] as $key => $all ) foreach( $all as $i => $val ) $files[$i][$key] = $val; $files_uploaded = array(); for ($i=0; $i < count($files); $i++) { $_FILES[$field] = $files[$i]; if ($this->upload->do_upload($field)) $files_uploaded[$i] = $this->upload->data($files); else $files_uploaded[$i] = null; } return $files_uploaded; } 

en tu caso:

  

o

    

en el controlador:

 public function do_upload(){ $config['upload_path'] = './Images/'; $config['allowed_types'] = 'gif|jpg|png'; //... $this->load->library('upload',$config); if ($_FILES['images']) { $images= $this->_upload_files('images'); print_r($images); } } 

Algunas referencias básicas del manual de PHP : carga de archivos PHP

Guarde, luego redefina la variable $ _FILES a lo que necesite. tal vez no sea la mejor solución, pero esto funcionó para mí.

 function do_upload() { $this->load->library('upload'); $this->upload->initialize($this->set_upload_options()); $quantFiles = count($_FILES['userfile']['name']); for($i = 0; $i < $quantFiles ; $i++) { $arquivo[$i] = array ( 'userfile' => array ( 'name' => $_FILES['userfile']['name'][$i], 'type' => $_FILES['userfile']['type'][$i], 'tmp_name' => $_FILES['userfile']['tmp_name'][$i], 'error' => $_FILES['userfile']['error'][$i], 'size' => $_FILES['userfile']['size'][$i] ) ); } for($i = 0; $i < $quantFiles ; $i++) { $_FILES = ''; $_FILES = $arquivo[$i]; if ( ! $this->upload->do_upload()) { $error[$i] = array('error' => $this->upload->display_errors()); return FALSE; } else { $data[$i] = array('upload_data' => $this->upload->data()); var_dump($this->upload->data()); } } if(isset($error)) { $this->index($error); } else { $this->index($data); } 

}

la función separada para establecer la configuración

 private function set_upload_options() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'xml|pdf'; $config['max_size'] = '10000'; return $config; }