简体   繁体   中英

Error with Ajax Jquery file upload in codeigniter

I am trying to upload file using ajax in codeigniter framework. But i got error message 'You did not select a file to upload.' Please check this code

View

<form method="POST" action="" enctype="multipart/form-data" id="file_upload">
<input type="file" id="file-input" name="file">
</form>

JQuery

$("#file-input").change(function() {
    var formData = new FormData($('#file_upload')[0]);    
    $.ajax({
        url : 'do_upload',
        data: formData,
        type:'POST',
        mimeType: "multipart/form-data",
        cache: false,
        contentType: false,
        processData: false,
        //  dataType:'json',
        success:function(data){
            alert(data);
        }
    });
});

controller

public  function do_upload(){
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload('file'))
    {
        echo  $this->upload->display_errors() ; 
    }
    else
    {
        echo "Uploaded";
    }
}

It doesn't look like the URL is pointing to a page or function that you have created. Try this: -

 $("#file-input").change(function() { var formData = new FormData($('#file_upload')[0]); $.ajax({ url : '<?php echo base_url('do_upload'); ?>', data: formData, type:'POST', mimeType: "multipart/form-data", cache: false, contentType: false, processData: false, // dataType:'json', success:function(data){ alert(data); } }); }); 

Your url is wrong in AJAX request

It should be url : '<?php echo site_url('controllerName/do_upload'); ?>', url : '<?php echo site_url('controllerName/do_upload'); ?>',

Also use

<?php echo form_open_multipart('', array('id' => 'file_upload')); ?>  

for form opening AND

<?php echo form_close(); ?> 

for form closing

Let me know if you require any further help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM