user1664427
user1664427

Reputation: 235

Why, when uploading files via Ajax, is CodeIgniter throwing a "no file uploaded" error?

All I'm trying to do is upload files using ajax to my CodeIgniter based website. But for some reason CodeIgniter keeps giving the "no file uploaded" error. How can I resolve this?

Here is the JavaScript:

<script type="text/javascript">
function updatebgimage()
    {   
        regexp = /^[^[\]]+/;
        var imgfile = document.getElementById("imagetoresize"); 
        var fileInputName = regexp.exec( imgfile['name'] ); 
        formdata = new FormData(); 
        formdata.append("imagetoresize",imgfile.files[0]);
        $.ajax({  
            url: "<?php echo site_url('uploadbgimage'); ?>",  
            type: "POST",  
            data: formdata,  
            dataType: "json",
            processData: false,  
            contentType: false,  
            success: function (data) {  
                    alert(data.message); 
            }  
        });  
    } 
</script>

Here is the CodeIgniter controller being called:

public function uploadbgimage()
{
    $config['upload_path'] = './images/stores/'.$memberid.'/'; 
    $config['file_name'] = 'main_bg_image.jpg'; 
    $config['allowed_types'] = 'jpg|png'; 
    $config['overwrite'] = true;       
    $this->load->library('upload', $config);  
    $data = array();
    if (! $this->upload->do_upload("bgimage"))
    {
        $data['result'] = 'fail';
    $data['message'] = $this->upload->display_errors();  
    } 
    else 
    {
         $data['result'] = 'success';
     $data['message'] = 'file was uploaded fine';  
    }
    echo json_encode($data);
}

Here is the HTML:

<form method="post" enctype="multipart/form-data">
     <input type="file" id="imagetoresize" name="imagetoresize" value="" class="field1" /> 
     <input type="button" onclick="updatebgimage()" value="UploadBGImage" /> 
</form>

Upvotes: 0

Views: 786

Answers (1)

thedayofcondor
thedayofcondor

Reputation: 3876

Shouldn't it be:

formdata.append("imagetoresize",imgfile.file);

See https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

Upvotes: 1

Related Questions