简体   繁体   中英

Ajax image upload error in Codeigniter 3

Hello I'm using Codeigniter 3 and jQuery ajax.

I'm using the built in upload library...

I want to upload image on my server, but always get this error message:

You did not select a file to upload.

Here is my code

View

<?php echo form_open_multipart('settings/uploadprofilephoto', array('id' => 'upload-avatar-form'));?>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Upload profile photo</h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <div class="row">
                    <div class="form-group col-md-6">
                            <input type="file" name="profilephoto" id="profile-photo" class="form-control">
                    </div>
                    <div class="form-group col-md-6">
                        <button type="submit" id="upload" class="btn btn-success">Upload</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal -->
<?php echo form_close();?>

Controller

public function uploadProfilePhoto(){

        $config = array(
            'upload_path' => base_url() . 'uploads/test',
            'allowed_types' => 'jpg|jpeg|gif|png',
            'min_height' => 480,
            'min_width' => 640,
            'remove_spaces' => true,
        );

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

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

            $data = array(
                'status' => true,
                'messages' => 'Uploaded'
            );

            echo json_decode($data);

        }else{

            $data = array(
                'status' => false, 
                'messages' =>  $this->upload->display_errors()
            );

            echo json_encode($data);
        }

    }

ajax

/* 
Upload profile photo
*/
$("#upload-avatar-form").submit(function(event){
    $.post(base_url + "settings/uploadprofilephoto" , $(this).serialize(), function(data){
        console.log(data);
       //alert("ok");
    });
    event.preventDefault();
});

Where am I wrong?

serialize() will not pass image within it. It does not work with multipart formdata.

Instead use like this: var formData = new FormData(this);

Pass this formData variable instead of $(this).serialize()

Try this

$('#button_name').on('click', function(event) { 

    event.preventDefault();

    $.ajax({
        url: "<?php echo base_url('settings/uploadprofilephoto');?>",
        type: 'post',       
        dataType: 'json',
        data: new FormData(this),
        cache: false,
        contentType: false,
        processData: false,     
        success: function(json) {
            // Success Stuff
        },          
    });
}); 

On the view part

<button type="button" id="button_name">Upload</button>

You have to try this

$('#logo_form').on('submit',function(form){
                   form.preventDefault(); 
                   var me = $(this);

                   var file_data = $('#file').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: me.attr('action'), // point to server-side controller method
                        dataType: 'text', // what to expect back from the server
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $("#logo_form")[0].reset();
                            $('#logo_success').html(response); // display success response from the server
                            window.setTimeout(function(){location.reload()},1000);
                        },
                        error: function (response) {
                            $('#error').html(response); // display error response from the server
                        }
                    });
                });

Please check below mentioned solution, This will help you to send file with input data.

 var myFormData = new FormData(); $(document).on("click", "button", function(e) { e.preventDefault(); var inputs = $('#my_form input[type="file"]'); $.each(inputs, function(obj, v) { var file = v.files[0]; var filename = $(v).attr("data-filename"); var name = $(v).attr("id"); myFormData.append(name, file, filename); }); var inputs = $('#my_form input[type="text"]'); $.each(inputs, function(obj, v) { var name = $(v).attr("id"); var value = $(v).val(); myFormData.append(name, value); }); var xhr = new XMLHttpRequest; xhr.open('POST', '/echo/html/', true); xhr.send(myFormData); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="my_form" enctype="multipart/form-data"> <input type="file" name="file_1" id="file_1" data-filename="image.jpg"><br /> <input type="text" name="check1" id="check1"/><br /> <input type="text" name="check2" id="check2"/><br /> <input type="text" name="check3" id="check3"/><br /> <button>Submit</button> </form> 

Let me know if it not works.

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