在codeigniter中使用AJAX上载文件时出错

时间:2015-12-29 11:21:29

标签: php jquery ajax codeigniter

我在codeigniter中创建一个管理面板。我有桌上游戏。它里面有一个图像。我想使用ajax上传该图像。但由于某种原因,图像没有被上传,并且没有选择文件就会发生错误。

控制器

public function ajax_add() {
    $this->_validate();

    $config = [
        'upload_path' => './assets/game_images/',
        'allowed_types' => 'gif|png|jpg|jpeg'
    ];
    $this->load->library('upload', $config);
    if ($this->upload->do_upload()) {
        $file = $this->upload->data();
        $file_name = $file['file_name'];

        if ($file_name == '') {
            $data['error_string'][] = 'Please upload an image.';
            $data['status'] = FALSE;
            echo json_encode($data);
            exit();
        }
    } else {
        $data['inputerror'][] = 'image';
        $data['error_string'][] = $this->upload->display_errors();
        $data['status'] = FALSE;
        echo json_encode($data);
        exit();
    }

    $data = array(
        'title' => $this->input->post('title'),
        'iframe' => $this->input->post('iframe'),
        'status' => $this->input->post('status'),
        'category_id' => $this->input->post('category_id'),
        'image' => $file_name
    );
    $insert = $this->game->save($data);
    echo json_encode(array("status" => TRUE));
}

public function ajax_update() {
    $this->_validate();
    $data = array(
        'title' => $this->input->post('title'),
        'iframe' => $this->input->post('iframe'),
        'status' => $this->input->post('status'),
        'category_id' => $this->input->post('category_id')
    );
    $this->game->update(array('id' => $this->input->post('id')), $data);
    echo json_encode(array("status" => TRUE));
}

HTML

<div class="container">
    <h1 style="font-size:20pt">Games</h1>
    <h3>Game Data</h3>
    <br />
    <button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
    <button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
    <br />
    <br />
    <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Status</th>
                <th style="width:125px;">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>

        <tfoot>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </tfoot>
    </table>
</div>

的Javascript

<script type="text/javascript">

    var save_method; //for save method string
    var table;

    $(document).ready(function () {

        //datatables
        table = $('#table').DataTable({
            "processing": true, //Feature control the processing indicator.
            "serverSide": true, //Feature control DataTables' server-side processing mode.
            "order": [], //Initial no order.

            // Load data for the table's content from an Ajax source
            "ajax": {
                "url": "<?php echo site_url('game/ajax_list') ?>",
                "type": "POST"
            },
            //Set column definition initialisation properties.
            "columnDefs": [
                {
                    "targets": [-1, -3], //last column
                    "orderable": false, //set not orderable
                },
            ],
        });

        //set input/textarea/select event when change value, remove class error and remove text help block 
        $("input").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });
        $("textarea").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });
        $("select").change(function () {
            $(this).parent().parent().removeClass('has-error');
            $(this).next().empty();
        });

    });



    function add_game()
    {
        save_method = 'add';
        $('#form')[0].reset(); // reset form on modals
        $('.form-group').removeClass('has-error'); // clear error class
        $('.help-block').empty(); // clear error string
        $('#modal_form').modal('show'); // show bootstrap modal
        $('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
    }

    function edit_game(id)
    {
        save_method = 'update';
        $('#form')[0].reset(); // reset form on modals
        $('.form-group').removeClass('has-error'); // clear error class
        $('.help-block').empty(); // clear error string

        //Ajax Load data from ajax
        $.ajax({
            url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function (data)
            {

                $('[name="id"]').val(data.id);
                $('[name="title"]').val(data.title);
                $('[name="iframe"]').val(data.iframe);
                $('[name="status"]').val(data.status);
                $('[name="category_id"]').val(data.category_id);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title

            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error get data from ajax');
            }
        });
    }

    function reload_table()
    {
        table.ajax.reload(null, false); //reload datatable ajax 
    }

    function save()
    {
        $('#btnSave').text('saving...'); //change button text
        $('#btnSave').attr('disabled', true); //set button disable 
        var url;

        if (save_method == 'add') {
            url = "<?php echo site_url('game/ajax_add') ?>";
        } else {
            url = "<?php echo site_url('game/ajax_update') ?>";
        }

        // ajax adding data to database
        $.ajax({
            url: url,
            type: "POST",
            data: $('#form').serialize(),
            dataType: "JSON",
            success: function (data)
            {

                if (data.status) //if success close modal and reload ajax table
                {
                    $('#modal_form').modal('hide');
                    reload_table();
                } else
                {
                    for (var i = 0; i < data.inputerror.length; i++)
                    {
                        $('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                        $('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
                    }
                }
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled', false); //set button enable 


            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error adding / update data');
                $('#btnSave').text('save'); //change button text
                $('#btnSave').attr('disabled', false); //set button enable 

            }
        });
    }

    function delete_game(id)
    {
        if (confirm('Are you sure delete this data?'))
        {
            // ajax delete data to database
            $.ajax({
                url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
                type: "POST",
                dataType: "JSON",
                success: function (data)
                {
                    //if success reload ajax table
                    $('#modal_form').modal('hide');
                    reload_table();
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error deleting data');
                }
            });

        }
    }

</script>

<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h3 class="modal-title">Game Form</h3>
            </div>
            <div class="modal-body form">

                <?php
                $attributes = array(
                    'id' => 'form',
                    'class' => 'form-horizontal'
                );

                echo form_open_multipart('#', $attributes);
                ?>
                <input type="hidden" value="" name="id"/> 
                <div class="form-body">
                    <div class="form-group">
                        <label class="control-label col-md-3">Title</label>
                        <div class="col-md-9">
                            <input name="title" placeholder="Title" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Iframe</label>
                        <div class="col-md-9">
                            <textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Category</label>
                        <div class="col-md-9">
                            <select name="category_id" class="form-control">
                                <option value="">--Select Category--</option>
                                <?php foreach ($categories as $category) { ?>
                                    <option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
                                <?php } ?>
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Image</label>
                        <div class="col-md-9">
                            <?php echo form_upload(['name' => 'image']); ?>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Status</label>
                        <div class="col-md-9">
                            <select name="status" class="form-control">
                                <option value="">--Select Status--</option>
                                <option value="0">Inactive</option>
                                <option value="1">Active</option>
                            </select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->

4 个答案:

答案 0 :(得分:2)

注意到您在代码中错过了几个必要条件

首先使用ajax_add方法

if ($this->upload->do_upload())这应该包含图像字段名称,如

if ($this->upload->do_upload('image')){// as your file upload field name is "image"

}

然后为ajax上传你的客户端代码,有些参数缺失

 contentType: false,
 processData: false,

所以你的ajax方法应该(在save方法中)看起来像

$.ajax({
        url: url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        contentType: false,
        processData: false
       .....

processData这在通过ajax上传文件时非常重要

答案 1 :(得分:1)

除了Rejoanul的建议之外,您可能还想检查是否没有上传过大的文件。

显然,如果您尝试上传的文件大于maxsize,则FILES变量将为空。

https://stackoverflow.com/a/21633123/2153218

答案 2 :(得分:0)

尝试更改控制器中的此行

{{1}}

答案 3 :(得分:0)

试试这个

$config = array( 'upload_path' => './assets/game_images/',
                  'allowed_types' => 'gif|png|jpg|jpeg'
                  'overwrite' => TRUE, );

get_instance()->load->library('upload', $this->config); 
if($this->upload->do_upload('image')) { 
    echo "file upload success"; 
} else { 
    echo $this->upload->display_errors(); 
}