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.
Try this one
JS Code
$("#save").click(function()
{
var formData = new FormData();
$f1 = $('#file-upload');
$f2 = $('#imgupload');
formData.append('file-upload', $f1.get(0).files[0]);
formData.append('imgupload', $f2.get(0).files[0]);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "comp/wfc",
data: formData,
processData: false,
contentType: false,
success: function(res)
{
console.log(res);
alert(res);
}
});
});
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"
<input type="file" multiple="multiple" id="file-upload" class="file-upload" name="file-upload" >
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).
$this->load->library('upload');
echo '<pre>';
print_r($_FILES);
$config['upload_path'] = './assets/file/.';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$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->upload->initialize($config2, true);
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'];
}
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.