Jc John Jc John - 20 days ago 11
jQuery Question

uploading an image in codeigniter trouble

I have a code from the tutorial and i dont know what happen's why mine doesn't work. I just follow the tutorial and the code doesn't work. I am using a codeigniter framework, please help me with these, i have no error in console also, i dont know what's happening why . Also it doesn't sends a request from ajax. Please check the code in ajax. Thanks.

ajax code:

$(function () {
var inputFile = $('input[name=file]');
var uploadURI = $('#form-upload').attr('action');

$('#upload-btn').on('click', function(event) {
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData();
formData.append("file", fileToUpload);
$.ajax({
url: uploadURI,
type: "POST",
data: formData,
processData: false,
contentData: false,
success: function(data) {
alert("Profile picture updated!");
}
});
}
});
});


from view :

<form action="<?php echo site_url("profile/profile_picture") ?>" id="form-upload">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput"><i class="glyphicon glyphicon-file fileinput-exists"></i> <span class="fileinput-filename"></span></div>
<span class="input-group-addon btn btn-default btn-file"><span class="fileinput-new"><i class="glyphicon glyphicon-paperclip"></i> Select file</span><input type="file" name="file"></span>
<a href="#" id="upload-btn" class="input-group-addon btn btn-success fileinput-exists"><i class="glyphicon glyphicon-open"></i> Upload</a>
</div>
</form>


controller:

public function profile_picture() {
$config['upload_path'] = "./assets/uploaded_images/";
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);

if($this->upload->do_upload("file")) {

}
else {
echo "File cannot be uploaded";
}
}


i got this error : enter image description here

File cannot be uploadedarray(1) {
["error"]=>
string(43) "<p>You did not select a file to upload.</p>"
}

Answer

OK the problem is it should be 'contentType' not 'contentData'. Here is updated JS code

$(function () {
    var inputFile = $('input[name=file]');
    var uploadURI = $('#form-upload').attr('action');

    $('#upload-btn').on('click', function(event) {
        var fileToUpload = inputFile[0].files[0];
        if(fileToUpload != 'undefine') {
            var formData = new FormData($('#form-upload')[0]);
            $.ajax({
                type: "POST",
                url: uploadURI,
                data: formData,
                processData: false,
                contentType: false,
                success: function(msg) {
                    alert("Profile picture updated!");
                }
            });
        }
    });
});