在codeigniter上传库中使用ajax上传图像

时间:2016-02-09 18:00:51

标签: jquery ajax codeigniter

您好我试图使用ajax上传单个图片,但我有这样的错误

<p>Severity: Warning</p>
 <p>Message:  Illegal offset type in isset or empty</p>
<p>Filename: core/Input.php</p>
<p>Line Number: 196</p>

这是我在视图中的代码 slider.php

//script

 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('slider/ajax_add')?>";
    } else {
      url = "<?php echo site_url('slider/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'+errorThrown);
        $('#btnSave').text('save'); //change button text
        $('#btnSave').attr('disabled',false); //set button enable 

    }
    });
    }

//end script

<div class="modal-body form">
                    <form  id="form" class="form-horizontal" enctype="multipart/form-data" method="post" accept-charset="utf-8">
                    <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="Caption" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>

                    <div class="form-group">

                        <div class="col-md-12">
                        <input type="file" name="userfile" class="form-control"/>
                            <span class="help-block"></span>
                        </div>
                    </div>



                </div>
            </form>
        </div>

控制器 slider.php

 public function __construct()
{
    parent::__construct();
    $this->load->model('slider_model','person');
}

public function ajax_add()
    {


    $this->_validate();
    $data = array(
            'title' => $this->input->post('title'),
            'image' => $this->input->post($this->upload()),
        );
    $insert = $this->person->save($data);
    echo json_encode(array("status" => TRUE));
}

 public function upload()
{
$config['upload_path'] = "./images/";
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$this->load->library('upload',$config);
if(!$this->upload->do_upload()) {
    $error = array('error' =>$this->upload->display_errors());
    echo $error;
}
else {
    $file_data = $this->upload->data();
    $filename = $file_data['file_name'];
    $this->main_m->save('title',$filename);
    $data['img'] = base_url().'/images/'.$file_data['file_name'];
    return $filename;
}
}

模型 slider_model.php

public function save($data)
{
    $this->db->insert($this->table, $data);
    return $this->db->insert_id();
}

我的代码有什么问题?如果我不使用ajax但是如果我使用ajax

则失败,该代码有效

1 个答案:

答案 0 :(得分:2)

您必须假设ajax contentType 属性,因此ajax不会设置内容类型,否则会将数据作为 url编码字符串发布到控制器方法并且您的文件资源将不可用。 我希望这个例子会有所帮助。

查看:

<form id="myform" action="<?= base_url('controller/method'); ?>" method="post">
    <input type="file" name="myfile">
</form>

<强>的Ajax

("#myform").submit(function(evt){
    evt.preventDefault();

    var url = $(this).attr('action');
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {
            console.log(res);
        },
        error: function (error) {
            console.log(error);
        }
    }); // End: $.ajax()           

}); // End: submit()

控制器:

public function upload_file()
{
    $this->load->library('upload');

    if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
    {
        if ($_FILES['myfile']['error'] != 4)
        {
             // Image file configurations
            $config['upload_path'] = './upload/';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $this->upload->initialize($config);
            $this->upload->do_upload('myfile');
        }
    }
}