Laravel: Updating multiple files in array - arrays

I was able to store and save multiple files in the array into the database, as well as updating the form data. However, the problem now is it returns this error when I update the form without updating the file.
count(): Parameter must be an array or an object that implements Countable
Does anyone know what should I do for my update function or value in my blade file so that it won't delete the file elements?
--------------------------------------------- UPDATED ---------------------------------------------
public function update(Request $request, $id)
{
$data = $request->all();
$data = $this->saveEmptyData($data);
$c = Document::find($id);
$fileData = [];
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('storage/documents');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc = json_encode($fileData);
$c->file = $doc;
$c->name = $request->name;
$c->price = $request->price;
$c->publish = $request->publish;
}
//else {
// redirect()->back()->with('errors', 'File is required!');
//}
$c->save();
return redirect()->route('product.index')->with('success', 'Document updated successfully');
}
Blade
<form method="POST" action="{{ route('document.update', $doc) }}" enctype="multipart/form-data">
<fieldset>
....
<div class="form-group">
<label>Document</label>
<div class="input-group-append">
<label for="upload_file">Upload</label>
<input id="upload_file" type="file" name="file[]" value="{{ isset($doc) ? $doc['file'] : '' }}" multiple>
</div>
</div>
</fieldset>
</form>

if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc= json_encode($fileData); //replace $doc['file'] with $doc
$c->file=$doc;
}
$c->save();
//not required to declare $fileData ;

enctype="multipart/form-data" in form tag
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc['file'] = json_encode($fileData);
}

Related

implode function not working in codeigniter

I want to store a checkbox array value by using implode function.when i stored,the database table value as Array (not a integer value show only array)
This is my view file:
<div class="col-sm-12">
<div>
<label class="form-control-label">Select Asset Type</label><br>
<div class="border-checkbox-section">
<div class="border-checkbox-group border-checkbox-group-primary">
<?php $b=0; foreach($assettype as $assettype_info){ $b++;?>
<input type="checkbox" name="assettype_name[]" class="border-checkbox" value="<?php echo $assettype_info->assettype_name; ?>" id="checkbox<?php echo $b;?>">
<label class="border-checkbox-label" for="checkbox<?php echo $b;?>"><?php echo $assettype_info->assettype_name; ?></label>
<?php } ?>
</div>
</div>
</div>
My Controller:
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(", ", $_POST['assettype_name']) ;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}
My Model :
Public function insertrecord($Table)
{
$Inputs=$_POST;
$Inputs["joinon"]=date("Y-m-d");
$Keys=array();
$Values=array();
foreach($Inputs as $Inp_key=>$inp_value)
{
if($Inp_key!="submit" && $Inp_key!="PHPSESSID")
{
$Keys[]= $Inp_key;
$Values[]= "'".$inp_value."'";
}
}
$keys=implode(',',$Keys);
$values=implode(',',$Values);
$qry="insert into ".$Table."(".$keys.") values(".$values.")";
$ack=$this->db->query($qry);
if($ack) return true; else return false;
}
I expected to store a array value as id with comma
DB shows as :
Db shows as
modified in controller to get the answer.
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(",",$_POST['assettype_name']) ;
$_POST['assettype_name'] = $assettype_name;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}

Codeigniter multiple file upload with input array key

I have two input field as below;
<input type="file" name="datainfo[site_logo]" class="custom-file-input" id="site_logo">
<input type="file" name="datainfo[site_fav]" class="custom-file-input" id="site_fav">
How can i upload two files with foreach ? I have tried a few methods but i couldnt achieve this.
Thanks,
Ok if you insist to keep it like that with your parameters and input names, then you have to restructure $_FILES array before do_upload():
public function upload()
{
$count = count($_FILES['datainfo']['name']);
for ($i=0; $i < $count; $i++)
{
foreach ($_FILES['datainfo'] as $key1 => $value1)
{
foreach ($value1 as $key2 => $value2)
{
$files[$key2][$key1] = $value2;
}
}
}
$_FILES = $files;
$config['upload_path'] = FCPATH.'uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload', $config);
foreach ($_FILES as $fieldname => $fileObject)
{
if (!empty($fileObject['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($fieldname))
{
$errors = $this->upload->display_errors();
}
else
{
$success = 'Success';
}
}
}
}
I've tested it in my environment with your inputs as it is and it works fine.

how to upload image to folder and path ot db in cakephp controller

i have written code in controller to move the uploaded file to folder ,but it was not working ,my code is
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a, '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
i think this line 'if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){ ... } was not working ,through this code i am able to store the '0 in my database i.e else part of the code.
how to move the uploaded image to folder and path to my database field..plz help me any one...!
my script code is
function addAdminList(){
var branchId = $('#branchId').val();
var branchName = $('#branchName').val();
var curiculumName = $('#curiculumName').val();
var owner = $('#owner').val();
var startdate = $('#startdate').val();
var phone = $('#phone').val();
var desc = $('#desc').val();
var address = $('#address').val();
var timings = $('#timings').val();
var image = $('#image').val();
if(!$("#addClsGrpFrm").validationEngine('validate')){
return false;
}
$('.overlay').show();
$.ajax({
url : '<?php echo BASE_PATH; ?>adminAjax/addAdminList',
type : 'POST',
data : {
branchId : branchId,
branchName : branchName,
curiculumName : curiculumName,
owner : owner,
startdate : startdate,
phone : phone,
desc : desc,
address : address,
timings : timings,
image : image
},
success : function(res){
$('.overlay').hide();
if(res == 0){
}
parent.$.colorbox.close();
oTable.fnDraw();
return false;
},
error : function(res){
alert('Server Error Occurred');
}
});
}
my form is
<form id="addClsGrpFrm" method="post" action="#" onsubmit="return disableFrmSubmit()">
<div class="flash_msg"><?php echo $this->Session->flash(); ?></div>
<input type="hidden" name="data[branch][id]" readonly id="branchId" value="0">
<div class="login-form">
<label>Shop Image</label>
<input type="file" id="image" data-prompt-position="topLeft:200" name="data[branch][image]" placeholder="" class="validate[required]" />
.....
</div>
<div class="login-form">
<input type="button" onclick="addAdminList()" class="login-btn" value="Submit">
</div>
<div class="clear"></div>
</form>
Some suggestions while submitting your form :
Use FormData when submitting your form rather than appending them one by one.
The extension extraction process that you are using in your controller may not save some files with "." in their filename.
I have created a test form for your knowledge.This is the form:
<form id="testForm" method="post" action="<?php echo 'http://localhost/blog/users/test'; ?>">
<input type="file" name="image" id="image">
<input type="submit" value="Submit">
</form>
You can use FormData like so:
$('#testForm').on('submit', function(event) {
event.preventDefault();
var form_data = new FormData($(this)[0]); // this will get all your form's inputs
$.ajax({
url:"<?php echo 'http://localhost/blog/users/test.json'; ?>", // you can use your form action URL here
type:'POST',
data:form_data,
processData: false,
contentType: false
});
});
and finally in your controller:
public function test() {
if ($this->request->is('post')) {
if (!empty($this->request->data['image']['tmp_name']) && is_uploaded_file($this->request->data['image']['tmp_name'])) {
$filename = basename($this->request->data['image']['name']);
$imagePath = WWW_ROOT . DS . 'documents' . DS . $filename; // save the file where you wish
move_uploaded_file(
$this->request->data['image']['tmp_name'],
$imagePath // save $imagePath in your database
);
}
}
}
You can use $imagePath to save in your database and as for your file extension process you can use this function as it will get the filetype even if the filename has a "dot" in it :
public function findFileTypeAndName($filename)
{
$split_point = '.';
$parts = explode($split_point, $filename);
$last = array_pop($parts);
$fileNameAndType = array(implode($split_point, $parts), $last);
return $fileNameAndType;
}
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a['tmp_name'], WWW_ROOT . '/img/uploads/users/' . basename($a['name']))){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
The issue is just that you tried to pass the image array to strrchr($a) instead of strrchr($a['name']) at this point:
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
Then you also tried to pass $a which is an array into move_uploaded_file($a,...).
Check my corrections for that part of the code...

Multiple files upload (Array) with CodeIgniter 2.0

I've been searching and struggling for 3 days now to make this works but I just can't.
What I want to do is use a Multiple file input form and then upload them. I can't just use a fixed number of file to upload. I tried many many solutions on StackOverflow but I wasn't able to find a working one.
Here's my Upload controller
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->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]);
}
}
}
}
}
?>
My upload form is This.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" multiple name="userfile[]" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
I just keep having this error :
You did not select a file to upload.
Here's the array of the example:
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] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 35266 [1] => 186448 ) ) )
I have this like 5 times in a row if I select 2 files.
I also use the standard Upload library.
I finally managed to make it work with your help!
Here's my code:
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;
}
Thank you guys!
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Installation Simply copy the MY_Upload.php file to your applications library directory.
Use: function test_up in controller
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 '<pre>';
print_r($this->upload->get_multi_upload_data());
echo '</pre>';
}
}else{
$this->load->view('test/upload_view');
}
}
upload_view.php in applications/view/test folder
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>
Try this code.
It's working fine for me
You must initialize each time the library
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("<span class='error'>", "</span>");
//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;
}
Further edit
I have found the way you must upload your files with one unique input box
CodeIgniter doesn't support multiple files. Using the do_upload() in a foreach won't be different than using it outside.
You will need to deal with it without the help of CodeIgniter. Here's an example https://github.com/woxxy/FoOlSlide/blob/master/application/controllers/admin/series.php#L331-370
https://stackoverflow.com/a/9846065/1171049
This is that said you in the commments :)
another bit of code here:
refer: https://github.com/stvnthomas/CodeIgniter-Multi-Upload
As Carlos Rincones suggested; don't be affraid of playing with superglobals.
$files = $_FILES;
for($i=0; $i<count($files['userfile']['name']); $i++)
{
$_FILES = array();
foreach( $files['userfile'] as $k=>$v )
{
$_FILES['userfile'][$k] = $v[$i];
}
$this->upload->do_upload('userfile')
}
All Posted files will be come in $_FILES variable, for use codeigniter upload library we need to give field_name that we are using in for upload (by default it will be 'userfile'), so we get all posted file and create another files array that create our own name for each files, and give this name to codeigniter library do_upload function.
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
}
}
}
}
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();
}
}
}
}
I have used below code in my custom library
call that from my controller like below,
function __construct() {<br />
parent::__construct();<br />
$this->load->library('CommonMethods');<br />
}<br />
$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />
// upload multiplefiles<br />
$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;
}
<form method="post" action="<?php echo base_url('submit'); ?>" enctype="multipart/form-data">
<input type="file" name="userfile[]" id="userfile" multiple="" accept="image/*">
</form>
MODEL : 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;
}
}
CONTROLER submit
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 '<pre>';
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 ';
}
}
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');
}
}
There is no predefined method available in codeigniter to upload multiple file at one time but you can send file in array and upload them one by one
here is refer: Here is best option to upload multiple file in codeigniter 3.0.1 with preview https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/
SO what I change is I load upload library each time
$config = array();
$config['upload_path'] = $filePath;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$files = $_FILES;
$count = count($_FILES['nameUpload']['name']);
for($i=0; $i<$count; $i++)
{
$this->load->library('upload', $config);
$_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
$_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
$_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
$_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
$_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];
$this->upload->do_upload('nameUpload');
}
And it work for me.
For CodeIgniter 3
<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
enctype="multipart/form-data">
<div class="form-group">
<label for="">title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="">File</label>
<input type="file" name="files" id="files" class="form-control">
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
public function insertdatanew()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['filesdua']['name']);
for ($i = 0; $i < $cpt; $i++) {
$_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
$_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
$_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
$_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
$_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];
// fungsi uploud
$config['upload_path'] = './uploads/testing/';
$config['allowed_types'] = '*';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('filesdua')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// $this->load->view('welcome_message', $error);
} else {
// menambil nilai value yang di upload
$data = array('upload_data' => $this->upload->data());
$nilai = $data['upload_data'];
$filename = $nilai['file_name'];
var_dump($filename);
// $this->load->view('upload_success', $data);
}
}
// var_dump($cpt);
}
I recently work on it. Try this function:
/**
* #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;
}
in your case:
<input type="file" multiple name="images[]" size="20" />
or
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
in the controller:
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);
}
}
Some basic reference from PHP manual: PHP file upload
Save, then redefine the variable $_FILES to whatever you need.
maybe not the best solution, but this worked for me.
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);
}
}
the separate function to establish the config..
private function set_upload_options()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'xml|pdf';
$config['max_size'] = '10000';
return $config;
}

Uploading multiple files userfile[] array?

I am trying to upload multiple images and I have a jquery plugin set up so I can browse for multiple files and select them.
The only problem I am having is accessing the file array in my controller, does anyone know how I can do this? Thanks.
view:
<input type="file" name="userfile[]" id="userfile" class="multi" />
I had this same issue on a project last year, after a bit of searching I found a perfect function.
I take no credit it for it, but cannot remmeber where I found it so if anyone knows please link back to the author.
Make sure the form has the files named like this
<input type="file" name="userfile"/>
<input type="file" name="userfile2" />
<input type="file" name="userfile3" /> ..etc
Or
<input type="file" name="userfile[]" />
The function..
function multiple_upload($upload_dir = 'uploads', $config = array())
{
$files = array();
if(empty($config))
{
$config['upload_path'] = '../path/to/file';
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '800000000';
}
$this->load->library('upload', $config);
$errors = FALSE;
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $this->upload->do_upload($key))
{
$data['upload_message'] = $this->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$this->load->vars($data);
$errors = TRUE;
}
else
{
// Build a file array from all uploaded files
$files[] = $this->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
#unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$this->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$this->lang->line('upload_no_file_selected').ERR_CLOSE;
$this->load->vars($data);
}
else
{
return $files;
}
}
Now it's been a while since I've used it so if you need any extra help setting it up just let me know.
To use Jquery multiple upload using html elements array [] developed as follows in the act of receiving data sobrescrevi the global variable $ _FILES PHP so that the function do_upload could read later. see:
#copy the original array;
$temp_array;
foreach($_FILES['fil_arquivo'] as $key => $val)
{
$i = 0;
foreach($val as $new_key)
{
$temp_array[$i][$key] = $new_key;
$i++;
}
//
}
$i = 0;
foreach($temp_array as $key => $val)
{
$_FILES['file'.$i] = $val;
$i++;
}
#clear the original array;
unset($_FILES['fil_arquivo']);
$upload_path = 'media/arquivos';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'doc|docx|xls|xlsx|ppt|pptx|pdf|txt|jpg|png|jpeg|bmp|gif|avi|flv|mpg|wmv|mp3|wma|wav|zip|rar';
$config['encrypt_name'] = true;
$this->upload->initialize($config);
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if($this->upload->do_upload($key))
{
$this->upload->data();
}
}
}
The HTML provided by ojjwood above will produce multiple input boxes. If you'd only like to have one input box but still upload multiple files, you need to include the attribute multiple="multiple" in your <input> element. The [] in name="userfile[]" allows the posted data to be an array and not just a single value.
On the Codeigniter/PHP side of things, you need to use $_POST['userfile] instead of $this->input->post('userfile') for working with arrays.

Resources