I have a form that requires a user to upload 2 files, file-upload & imgupload. I am trying to save the entire form through ajax.
Form and ajax code
<form enctype="multipart/form-data" id="data">
<input type="file" id="file-upload" class="file-upload" name="file-upload" >
<input type="file" id="imgupload" class="imgupload" name="imgupload" >
<button type="submit" id="save" class="save-icon-btn">
<img src="<?php echo base_url(); ?>assets/img/Save.png">
</button>
</form>
$("#save").click(function()
{
var form_data = new FormData($('#data')[0]);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "comp/wfc",
data: form_data,
processData: false,
contentType: false,
success: function(res)
{
console.log(res);
alert(res);
}
});
});
Controller code
$config['upload_path'] = './assets/file/.';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file-upload'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = $this->upload->data();
echo $res = $data['file_name'];
}
$config2['upload_path'] = './assets/img/.';
$config2['allowed_types'] = 'gif|jpg|png|doc|docx|txt';
$config2['max_size'] = 1024 * 8;
$config2['encrypt_name'] = TRUE;
$this->load->library('upload', $config2);
if (!$this->upload->do_upload('imgupload'))
{
$error1 = array('error' => $this->upload->display_errors());
print_r($error1);
}
else
{
$data1 = $this->upload->data();
echo $res1 = $data1['file_name'];
}
The issus is that in the controller code only 1 of the files get uploaded. If i keep file-upload as the first upload code then only this will get uploaded and imgupload will not get uploaded.
And if i keep imgupload as the first upload code then only this will get uploaded and file-upload will not get uploaded.
I am not able to understand why this is happening. Can anyone please tell a solution to this problem
Please try this updated function. You were doing some strange things e.g. initializing the first and not the second. As CI is a singleton, this could result in some issues (not saying that this was the root cause).
If it doesn't work. Please let us know what the
$_FILES
array is printing.UPDATE:
It wasn't working because
$this->load->library('upload', $config2);
. When CI sees load it checks first if the class is loaded regardless of the parameters being passed, as it was already loaded this line was ignored and the settings from$config
(the first image upload) were being used.Try this one
JS Code
FYI, You can try below too if you are not aware of
Instead of multiple file input try to the single file input with multiple = "multiple"