Hello everyone, I would like to share with you on how to upload array of files with Thumbnail in Code Igniter.
Here’s the step by step guide for you to follow:
In views, you can create a form including input files in an array then submit to the controller to be saved in a folder or directory where the upload path is located.
Views:
<form action="<?=base_url()?>upload_array_files" method="post" enctype="multipart/form-data">
<label for="url">Upload Files: </label>
<input type="file" name="files[]" value="" />
<input type="file" name="files[]" value="" />
<input type="file" name="files[]" value="" />
<input type="submit" value="Save Article/s">
</form>
Here’s the controller:
This function called upload_array files. In this process, all configurations in files were applied in an array.
Controllers:
function upload_array_files() {
$this->load->helper('form');
// config for all files in array the same
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|pdf';
$config['max_size'] = '1000';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form',$error);
} else {
for($i = 0, $t = count($_Files['files']); $i < $t; $i++) {
$id = $this->files->add_files($i);
}
}
redirect('home');
}
The files were uploaded and automatically create thumbnail, then apply all configurations for thumbnails in an array.
” for($i = 0, $t = count($files); $i < $t; $i++) { } " as shown in this model, the uploaded files from views were counted and used for loop. After this, the function of the model will be called and save to the table of the file uploaded, this function is called add_files.
In this model, the files were saved on the table.
Model:
function add_files($i) {
$file = $this->upload->data();
$files = $file['file_name'];
$fields = array(
'files' => $files[$i]
);
for ($i = 0; $i < count($files); $i++) {
$data['image'] = './uploads/'.$files[$i];
//$data['image'] = './uploads/'.$files[1];
$config['image_library'] = 'gd2';
$config['source_image'] = $data['image'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 345;
$config['height'] = 224;
$config['new_image'] = './uploads/thumb/'.$files[$i];
$this->load->library('image_lib');
//$this->image_lib->resize();
$this->image_lib->initialize($config); //MUST CALL THIS METHOD
if(!$this->image_lib->resize()){
//echo '<p> not resized</p>';
}else{
//echo '<p> OK </p>';
}
$this->image_lib->clear();
}
$this->db->set($fields);
$this->db->insert($this->files_table);
return $this->db->insert_id();
}
This is just one way to upload arrays with thumbnail. Using the power of internet, you can find more advanced programming to do this process. Watch out for more tutorial that we will publish soon.
