【问题标题】:uploading image in a form using codeigniter/ajax使用 codeigniter/ajax 在表单中上传图片
【发布时间】:2016-01-01 07:06:44
【问题描述】:

如果我无法以成功创建的形式上传图像但文件显示为 0 而不是上传文件,我该怎么办。请帮助我提前谢谢!

我可以通过上传更新和添加单个表单的视图中的脚本

 <script type="text/javascript">

var save_method; //for save method string
var table;
$(document).ready(function() {
  table = $('#dataTable2').DataTable({ 

    "processing": true, //Feature control the processing indicator.
    "serverSide": true, //Feature control DataTables' server-side processing mode.

    // Load data for the table's content from an Ajax source
    "ajax": {
        "url": "<?php echo site_url('about/ajax_list')?>",
        "type": "POST"
    },

    //Set column definition initialisation properties.
    "columnDefs": [
    { 
      "targets": [ -1 ], //last column
      "orderable": false, //set not orderable
    },
    ],

  });
});

function add_person()
{
  save_method = 'add';
  $('#form')[0].reset(); // reset form on modals
  $('#myModal').modal('show'); // show bootstrap modal
  $('.modal-title').text('Add About US'); // Set Title to Bootstrap modal title
}

function edit_person(about_id)
{
  save_method = 'update';
  $('#form')[0].reset(); // reset form on modals

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

        $('[name="about_id"]').val(data.about_id);
        $('[name="about_details"]').val(data.about_details);
        $('[name="images"]').val(data.image);


        $('#myModal').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Edit Person'); // 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()
{
  var url;
  if(save_method == 'add') 
  {
      url = "<?php echo site_url('about/ajax_add')?>";
  }
  else
  {
    url = "<?php echo site_url('about/ajax_update')?>";
  }

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

           //if success close modal and reload ajax table
           $('#myModal').modal('hide');
           reload_table();
           if (empty($_FILES['image'])) {          
        return FALSE;
    }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
}

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

  }
}

这是我的表格

<div class="modal-body form">

                  <form action="#" id="form">
                   <input type="hidden" value="" name="about_id"/> 
                        <!--                            <div class="form-group has-feedback ">
                                                        <label>Date</label>
                                                        <input type="date" id="date" class="form-control" input-sm placeholder="Date"/>
                                                    </div>-->
                        <div class="form-group has-feedback">
                            <label>About Details</label>
                            <input type="text" id="title" name="about_details" class="form-control" input-sm placeholder="About Details"/>
                        </div>




                        <!-- Description -->

                        <div class="form-group has-feedback">
                           <label>Image</label>
                            <?php $attrib = array('type'=>'text','name'=>'image','class'=>'form-control','id'=>'file'); ?>
        <?php echo form_upload( $attrib,set_value('image')); ?>

                    </form>   

                    <div class="modal-footer">
                        <button type="button"  class="btn btn-default pull-left" data-dismiss="modal">Close</button>
                          <button type="button" id="btnSave" class="btn btn-success"  aria-hidden="true" onclick="save()">Save</button>

用于添加和更新的控制器

public function ajax_add()
{

    $data = array(
            'about_details' => $this->input->post('about_details'),
            'image' => $this->upload->do_upload('image'),



        );
    $insert = $this->person->save($data);
    echo json_encode(array("status" => TRUE));
}

public function ajax_update()
{
    $data = array(
            'about_details' => $this->input->post('about_details'),
            'image' => $this->upload->do_upload('image'),

        );
    $this->person->update(array('about_id' => $this->input->post('about_id')), $data);
    echo json_encode(array("status" => TRUE));
}

【问题讨论】:

    标签: javascript php ajax codeigniter


    【解决方案1】:

    我在 CodeIgniter 中通过 ajax 上传时发现,当我们提交表单时,图像不会被上传。因此,我使用了一个额外的 js 文件“jquery.form.min.js”,并且 ajax 上传顺利。要实现它,脚本如下所示:

    $('#uploadimg').ajaxForm({
           //uploadimg is my form id            
            dataType: 'json',
            success: processJson
    });
    function processJson(data) {
            if(data.msg=="success"){
                 alert('Upload is successful.');
            }
            else{
                 alert('Upload couldn't be completed.');
            }
    }
    

    表格是

    <form action="<?=base_url();?>controller/uploadImage/" method="post" enctype="multipart/form-data" id="uploadimg">
    

    在提交时,这将调用控制器中的 uploadImg 函数,并在此处保存图像并插入数据库。

    public function uploadImage(){
        //$id = $this->session->userdata('uid');
        $config[ 'upload_path' ]   = UPLOAD_DIR.'/newsletter/0';
        $config[ 'allowed_types' ] = 'gif|jpg|png';
        $config[ 'max_size' ]      = '1500';
        $config[ 'max_width' ]     = '1000';
        $config[ 'max_height' ]    = '1500';
        $image_name                = "files";
        $this->load->library( 'upload', $config );
        if ( $this->upload->do_upload( $image_name ) ) {
                $upload_data = $this->upload->data();
                if(!empty($upload_data)){
                    $arg = array(
                                'name' => $upload_data[ 'file_name' ]
                    );
                    $this->modelName->insert($arg );
                    $data['msg']="success";
                }
                else{
                    $data['errmsg']="Couldnot upload the file!";
                }
        }
        else{
            $data['errmsg'] =$this->upload->display_errors();
        }
        echo json_encode($data);
    }
    

    现在这将触发脚本中的 processJson 函数。并且上传显示结果。

    您可以在 jquery.form.js 上找到 javascript 文件。

    我希望它对你有用。

    【讨论】:

    • wupendra 我有一张包含图片的表格。然后我也有一个包含图像的表单,所以我需要在我的 ajax 和控制器文件中编辑我的函数,我可以在其中将图像文件保存到用户上传的数据库中。
    • 我可以上传图片,但没有保存到数据库中
    • 文件夹中是否包含上传的图片?
    • 没有上传任何内容,也没有保存到数据库中。
    • 您还没有调用控制器上的库函数。如果您按照上述步骤操作,它将起作用。
    猜你喜欢
    • 2014-10-04
    • 2012-03-25
    • 1970-01-01
    • 2012-05-29
    • 2015-01-31
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多