I do know how to upload an image by ajax in a traditional way. However, with the library upload
from CodeIgniter I can't figure it out.
But first, let me just tell you that I do not use a form at all.
if(!empty($_FILES)){
$this->load->helper('global_helper');
$config['upload_path'] = base_url() + "public/images/";
$config['file_name'] = randomName();
$config['allowed_types'] = "jpg|png|bmp";
$config['max_size'] = '500';
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
This does not work because I'm receiving the following error:
Array
(
[error] => <p>You did not select a file to upload.</p>
)
But I actually did and it was actually uploaded to the server, because if I print out the $_FILES
I receive:
Array
(
[0] => Array
(
[name] => no_image.png
[type] => image/png
[tmp_name] => C:\xampp\tmp\php1715.tmp
[error] => 0
[size] => 6361
)
)
Might be the problem of the input being in an Array(of Array[0])?
The javascript code is the following:
event.stopPropagation();
event.preventDefault();
var data = new FormData();
if(picture != undefined){
$.each(picture, function (key, value) {
data.append(key, value);
});
}
$.ajax({
url: 'ajax_add',
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function(aux){
console.log(aux);
}
});
I do not want to use the traditional way, but if I have too..
Thanks.
Not sure if it can work, because the file uploading class is designed to be used with a form, but you can try this
$this->upload->do_upload(0);
If it does what I think, it will select the first item of the $_FILES
array. By default, it tries to find $_FILES['userfile']
, who doesn't exists here (which is why you have the error).
Give it a try, and we'll see if it works :)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments