使用Bootsrap Modal上传图像

Uploading Image with Bootsrap Modal

本文关键字:图像 Modal Bootsrap 使用      更新时间:2023-12-05

我在使用bootsrap模式上传图像时遇到了一些问题。问题是,即使我选择了一张图片,我也总是会收到验证错误"你的上传表单是空的"。

这是我在上查看的表格

<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">User Form</h3>
        </div>
        <div class="modal-body form">
            <form action="#" id="form" class="form-horizontal" enctype="multipart/form-data">
                <input type="hidden" value="" name="id_berita"/>
                <div class="form-body">
                    <div class="form-group">
                        <label class="control-label col-md-3">Judul Berita</label>
                        <div class="col-md-9">
                            <input name="judul_berita" placeholder="Judul Berita" class="form-control" type="text">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Isi Berita</label>
                        <div class="col-md-9">
                            <textarea name="isi_berita" placeholder="Isi Berita Ini" class="form-control"></textarea>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-md-3">Foto Berita</label>
                        <div class="col-md-9">
                            <input type="file" name="foto_berita" class="form-control">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <input type="hidden" value="<?php echo $id_ses; ?>" name="id_user"/>
                <input type="hidden" value="<?php $tgl=date("Y-m-d");echo $tgl;?>" name="postdate"/>
                <input type="hidden" value="<?php date_default_timezone_set('Asia/Taipei');$jam=date("H:i:s");echo $jam;?>" name="waktu"/>
                </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 -->

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('databerita/ajax_list')?>",
        "type": "POST"
    },
    //Set column definition initialisation properties.
    "columnDefs": [
    {
        "targets": [ -1 ], //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_berita(){
   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 Berita'); // Set Title to Bootstrap modal title
}
function edit_berita(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('databerita/ajax_edit/')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {
        $('[name="id_berita"]').val(data.id_berita);
        $('[name="judul_berita"]').val(data.judul_berita);
        $('[name="isi_berita"]').val(data.isi_berita);
        $('[name="id_user"]').val(data.id_user);
        $('[name="postdate"]').val(data.postdate);
        $('[name="waktu"]').val(data.waktu);
        $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Edit Berita'); // 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('databerita/ajax_add')?>";
} else {
    url = "<?php echo site_url('databerita/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_berita(id){
if(confirm('Are you sure delete this data?'))
{
    // ajax delete data to database
    $.ajax({
        url : "<?php echo site_url('databerita/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');
        }
    });
}
}

控制器

public function ajax_add()
{
    $this->_validate();
    $nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
    $config['upload_path'] = './assets/images/'; //path folder
    $config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
    $config['max_size'] = '2048'; //maksimum besar file 2M
    $config['max_width']  = '1288'; //lebar maksimum 1288 px
    $config['max_height']  = '768'; //tinggi maksimu 768 px
    $config['file_name'] = $nmfile; //nama yang terupload nantinya
    $this->load->library('upload',$config);
    if($_FILES['foto_berita']['name']){
        if ($this->upload->do_upload('foto_berita')){
            $berita = $this->upload->data();
            $data = array(
              'judul_berita' =>$this->input->post('judul_berita'),
              'isi_berita' =>$this->input->post('isi_berita'),
              'foto_berita' =>$berita['file_name'],
              'id_user' =>$this->input->post('id_user'),
              'postdate' =>$this->input->post('postdate'),
              'waktu' =>$this->input->post('waktu'),
            );
            $insert = $this->m_databerita->save($data);
            echo json_encode(array("status" => TRUE));
        }
    }
}

谢谢你的帮助。

这里有一个例子,说明我如何在模式窗口中使用iFrame上传图片,这样做可以避免重新加载页面。我不知道是否可以使用ajax来实现,但这里有一种不同的方法。

首先在模态主体中添加iFrame,注意src是包含iFrame信息的视图:

<iframe id="photo_uploader" src="/image_form" class="picture-upload-iframe"></iframe>

这是iframe的src视图,如果您将多个iframe用于不同的目的,并且它们共享页眉和页脚,则会显示header.php和footer.php:

<? include('header.php');?>
<?= form_open_multipart('items/item_image_upload');?>
    <input id="upload-btn" name="userfile" type="file" class="upload" />
    <button class="btn btn-primary" name="submit" type="submit" class="btn">
</form>
<? include('footer.php');

现在在你的控制器中,这只是一个示例函数,如果你需要在上传图片时提交iFrame中的所有其他字段,你可以添加它们,然后做你需要做的事情。我只是返回true或false,看看上传是否成功。

public function item_image_upload()
{
    $data['file_name']        = false;
    $data['error']            = false;
    $config['allowed_types']  = 'gif|jpg|png';
    $config['upload_path']    = $this->img_full;
    $config['encrypt_name']   = true;
    $config['remove_spaces']  = true;
    $this->load->library('upload', $config);
    if ( $this->upload->do_upload())
    {
        $upload_data    = $this->upload->data();
        return true;
    }
    return false;
 }