How to make automatically upload any images when user choose images without submit?

2.3k views Asked by At

I'm creating the ability to automatically upload images with Codeigniter and jquery Ajax. Users will select their images from their computer and then Ajax will send to server by Post.

Issue: Images couldn't be uploaded to server and after Ajax responded I got an empty image property. It seems to be that my form couldn't be valid but I still can't find the solution.

Result: After Ajax responded my res variable can't get any data.

Here is my controller

public function upload() {

        $this->load->helper(array('form', 'url'));
        $config['upload_path'] = './uploads/';
        $config['image_library'] = 'gd2';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->load->library('upload', $config);
        $token = $this->security->get_csrf_hash();
        $data = array();
        $res = FALSE;
        if (!$this->upload->do_upload('userfile')) {
//            $data = $this->upload->data();
            $res = FALSE;
        } else {

            $res = TRUE;
            $this->upload->do_upload('userfile');
            $data = $this->upload->data();
        }
        echo json_encode(array('res'=>$res,'img_pro'=>$data,'token'=>$token));
    }

Here is my form

<?php echo form_open_multipart('image/upload', array("class" => "form_horizontal", "id" => "images")); ?> 
<div class="col-lg-12 col-sm-12 col-xs-12 ">
    <div class="control-group" style="margin-top: 12px;height: 70px; width:100%;border:1px solid red;">
       <div class="controls form-group-sm">
            <span class="btn btn btn-success btn-lg btn-file">
            Select your images: <?PHP echo form_upload('userfile', '', 'id="userfile" class="userfile"') ?>
             </span>
          </div>
       </div>
    </div> 
 <?php echo form_close(); ?>

And here is my Ajax

<script type="text/javascript">
    $(document).ready(function () {
        $("#images input[name=userfile]").change(function () {
                $.ajax({
                    type: "post", 
                    url: "<?php echo base_url('image/upload'); ?>",
                    data: {
                        '<?PHP echo $this->security->get_csrf_token_name(); ?>': '<?PHP echo $this->security->get_csrf_hash(); ?>',
                        userfile: $("#userfile").val()
                    },
                    dataType: "json",
                    cache: false,
                    success: function (data) {
                        console.log(data);
                        console.log($("#userfile").val());
                    }
                }); 
        });
    });
</script>

Here is the output

{
  "res":false,
  "img_pro":{
    "file_name":"",
    "file_type":"",
    "file_path":".\/uploads\/",
    "full_path":".\/uploads\/",
    "raw_name":"",
    "orig_name":"",
    "client_name":"",
    "file_ext":"",
    "file_size":null,
    "is_image":false,
    "image_width":null,
    "image_height":null,
    "image_type":"",
    "image_size_str":""
  },
  "token":"7a3f48fc1d4bec708e2ab338ddf96038"
}
1

There are 1 answers

0
AsgarAli On BEST ANSWER
$("#userfile").change(function (objEvent) {
    var objFormData = new FormData();
    // GET FILE OBJECT
    var objFile = $(this)[0].files[0];
    // APPEND CSRF TOKEN TO POST DATA
    objFormData.append('<?= $this->security->get_csrf_token_name(); ?>', '<?= $this->security->get_csrf_hash(); ?>');
    // APPEND FILE TO POST DATA
    objFormData.append('userfile', objFile);
    $.ajax({
        url: "<?= base_url('image/upload'); ?>",
        type: 'POST',
        contentType: false,
        data: objFormData,
        //JQUERY CONVERT THE FILES ARRAYS INTO STRINGS.SO processData:false
        processData: false,
        success: function (data) {
        }
    });
});