【问题标题】:How to upload image in codeigniter using ajax with server validation如何使用带有服务器验证的 ajax 在 codeigniter 中上传图像
【发布时间】:2017-10-29 11:41:20
【问题描述】:

我有一个表单,数据通过 ajax 插入到数据库中。随着输入字段出现错误,然后在每个字段下显示错误。

但是当我选择图片并尝试将图片的名称上传到数据库时,没有任何反应,既没有上传图片到上传路径,也没有将图片的名称插入数据库。

在图片上传错误的情况下,我什至无法显示图片上传错误。

控制器:- 在我的控制器中,您可以看到我有一个名为 result 的数组,它有两个键状态和消息,默认状态为 false。

在 else 部分,一个循环正在运行,它只有表单错误,没有任何类型的图像错误,这可能是没有显示任何图像错误的原因。

如果没有显示错误,没问题,但至少应该插入文件名。

function infoValidation() {

$result = array('status' => false, 'message' => array());

$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if ($this->form_validation->run('company_registration')) {
        $config['upload_path']       = 'assets/uploads/';
        $config['allowed_types']     = 'gif|jpg|jpeg|png';

        $this->load->library('upload',$config); 
        $this->upload->initialize($config);
        if ($this->upload->do_upload('image'))
        {
            $data['upload_data'] = $this->upload->data('file_name');
            $image_name = $data['upload_data'];
            //$result['message'] = $this->upload->display_errors();
            //$result['status'] = false;
        }
        else
        {
            $image_name = '';   
        }

        $data = array(

            'email'         => $this->input->post('email'),
            'first_name'    => $this->input->post('firstname'),
            'last_name'     => $this->input->post('lastname'),
            'pincode'       => $this->input->post('pincode'),
            'state'         => $this->input->post('state'),
            'landmark'      => $this->input->post('landmark'),
            'address'       => $this->input->post('address'),
            'state'         => $this->input->post('state'),
            'image'         => $image_name,
            'joined_date'   => date('Y-m-d H:i:s')
            );


        $result['status'] = true;

        $this->Perfect_mdl->c_insert($data);


}else {


    foreach ($_POST as $key => $value) {

        $result['message'][$key] = form_error($key);
    }
}

echo json_encode($result);

}

Ajax:

$("#form").submit(function(e){
    e.preventDefault();
    var me = $(this);

    $.ajax({
        url : me.attr('action'),
        dataType : 'json',
        type : 'POST',
        data : me.serialize(),
        success: function(resp) {
            console.log(resp);
            if (resp.status == true) {
                $('#myModal').modal('show');

                $(".form-group").removeClass('has-error').removeClass('has-success');
                $(".text-danger").remove();
            }else {
                $('#msg').html('<div class="alert alert-danger"><h5>Please Check Your Details</h5></div>');
                $.each(resp.message, function(key, value) {

                    var element = $("#"+key);
                        element.closest('.form-group')
                                .addClass(value.length > 0 ? 'has-error' : 'has-success')
                                .find('.text-danger').remove();

                        if(element.parent('.input-group').length) {
                            element.parent().after(value);
                        } else {
                            element.after(value);
                        }
                    // element.after(value);
                });
            }
        }
    });     
});

如何将图像上传到数据库中,如果这不是正确的方法,请提出正确的方法

【问题讨论】:

标签: php jquery ajax image codeigniter


【解决方案1】:

serialize() 方法无法发布文件数据。

使用 ajax 发送文件使用 FormData 而不是序列化

HTML5引入了FormData,允许开发者动态构建表单对象,然后通过AJAX发送这个表单对象。

查看

<form action="Your controller method name" method="post" id="form_img" enctype="multipart/form-data" accept-charset="utf-8">
        <div>
            username : <input type="text" name="name">
            <span class="error name"></span>
        </div>
        <div>
            password : <input type="text" name="password">
            <span class="error password"></span>
        </div>
        <div>
            file : <input type="file" name="image">
            <span class="error image"></span>
        </div>
        <input type="submit" name="submit" value="submit">
        </form>

Jquery 调用

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#form_img").submit(function(e){
            e.preventDefault();
            var formData = new FormData($("#form_img")[0]);

            $.ajax({
                url : $("#form_img").attr('action'),
                dataType : 'json',
                type : 'POST',
                data : formData,
                contentType : false,
                processData : false,
                success: function(resp) {
                    console.log(resp);
                    $('.error').html('');
                    if(resp.status == false) {
                      $.each(resp.message,function(i,m){
                          $('.'+i).text(m);
                      });
                     }
                }
            });
        });
    });

</script>

控制器

function test_image() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'name', 'required');
        $this->form_validation->set_rules('password', 'password', 'required');
        $this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
        if ($this->form_validation->run() == TRUE) {
            if($_FILES['image']['error'] != 0) {
                $result['status'] = false;
                $result['message'] = array("image"=>"Select image to upload");
            } else {
                $config['upload_path']       = 'images';
                $config['allowed_types']     = 'gif|jpg|jpeg|png';
                $this->load->library('upload',$config);
                $this->upload->initialize($config);
                if ($this->upload->do_upload('image'))
                {
                    $data['upload_data'] = $this->upload->data('file_name');
                    $image_name = $data['upload_data'];
                }
                else
                {
                    $image_name = '';
                }
                $data = array(

                'name'         => $this->input->post('name'),
                'password'    => $this->input->post('password'),
                'image'         => $image_name,
                'joined_date'   => date('Y-m-d H:i:s')
                );


                $result['status'] = true;
                $this->Perfect_mdl->c_insert($data);
                $result['message'] = "Data inserted successfully.";
            }
        }else {
            $result['status'] = false;
            // $result['message'] = validation_errors();
            $result['message'] = $this->form_validation->error_array();
        }
        echo json_encode($result);
    }

试试这个使用ajax上传图片的流程

【讨论】:

  • 如果我的控制器很好,为什么这没有显示任何图像上传错误。
  • 好的,我更新我的代码。检查控制器方法以使用表单验证库并插入数据。我为演示目的设计表单,您设置了您的表单...@vishalkumar
  • 现在这些验证错误将显示在一个地方。但是我怎样才能在每个字段下显示这个错误。 @尼迪
  • 谢谢..现在我有两种方法可以做到这一点@Nidhi
  • 哦,太好了...很高兴为您提供帮助,并感谢您接受它...@vishalkumar
【解决方案2】:

文件不能用serialize()函数上传,因为它不序列化文件。请尝试这种方法:

     var data = new FormData(this);

     $.ajax({
       url : me.attr('action'),
       dataType : 'json',
       contentType : false,
       processData : false,
       type : 'POST',
       data : data,
       success: function(resp) { ... etc.

【讨论】:

    【解决方案3】:

    在视图中尝试此代码

     $('#formElement').submit(function () {
             var formData = new 
              FormData(document.getElementById("formElement"));
                formData.append('image-file', $('#image-file')[0].files[0]);
    
                $.ajax({
                url: "<?php echo base_url('home/add')?>",
                data: formData,
                contentType: false, 
                processData: false,
                type: 'POST',
                beforeSend: function() {
                            $('.loder_img').show();    
                            },
                success: function ( data ) {
                   $('.loder_img').hide();    
                   var val = JSON.parse(data); 
                    //you can apply alerts or anything to show validation on 
                     view and in val all mesg of validation yon can see here in console.
                   console.log(val);
                },
                error: function (request, status, error) {
                    $('.loder_img').hide();   
                    alert(request.responseText);
                }
    
                });
      });
    

    在你的控制器中

     public function addPackage()
        { 
    
            $this->load->library("form_validation");
    
            //left side form
            $this->form_validation->set_error_delimiters('', '');
            $this->form_validation->set_rules('txt_desc', 'Remarks', 'required|trim');
            $this->form_validation->set_rules('txt_store', 'Store', 'required|trim');
        //upto so on according to your values
        if( $this->form_validation->run() == false){
        $error = array(
                                "check_1" => form_error('check_1'),
                                "txt_desc" => form_error('txt_desc'),
                                "txt_store" => form_error('txt_store'),
                                "txt_couple_name" => form_error('txt_couple_name'),
                                "txt_couple_case" => form_error('txt_couple_case'),
                                "txt_phone" => form_error('txt_phone'),
                                "txt_date" => form_error('txt_date'),
                                "txt_location" => form_error('txt_location'),
                                "txt_address" => form_error('txt_address'),
                                "txt_email" => form_error('txt_email'),
                                );
                        $msg = array('status' => 'invalid', 'msg' 
                                      =>$error,'allerror'=>validation_errors());
                            echo json_encode($msg);
            }else{
             //insert it into database all file and values
        if($_FILES["image-file"]["size"] != 0){ 
                            $path= './uploads/image';
                            $img = "image/".$this->Upload_model->image_upload($path, "", '', '', '',"image-file");
                        }
        $data = array(
                            "basket" => $this->filter($this->input->post("check_1",true))........
        );
        //your insert query
          }
        }
    

    在你的模型中上传图片,如果没有上传,它会返回上传的图片,它会返回 false 或者你可以打印显示错误,不要忘记更改存储图片的路径

    型号代码

    public function image_upload($upload_path, $max_width, $max_height, $min_width, $min_height, $filename)
        {
                $config['upload_path'] = $upload_path;
                $config['file_name'] = date('Ymd_his_').rand(10,99).rand(10,99).rand(10,99);
                $config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|bmp";
                $config['overwrite'] = FALSE;
                $config['max_size'] = '0';
                $config['max_width']  = $max_width;
                $config['max_height']  = $max_height;
                $config['min_width']  = $min_width;
                $config['min_height']  = $min_height;
                $config['max_filename']  = '0';
                $config['remove_spaces']  = FALSE;
    
                $this->load->library('upload', $config);
    
                if ( ! $this->upload->do_upload($filename))
                    {
                        /*$data['upload_data']['file_name'] = '';
                        $msg = $this->upload->display_errors('');
                        $this->session->set_flashdata('msg',$msg);  
                        $url = $_SERVER['HTTP_REFERER'];
                        redirect($url); */
                     return false;              
                     //return $error = array('error' => $this->upload->display_errors());               
                    }
                else
                    {
                        $data = array('upload_data' => $this->upload->data());
                        $config['source_image'] = $config['upload_path'].$data['upload_data']['file_name'];
                        $config['quality'] = '100%';
    
                        $this->load->library('image_lib', $config);
                        return $data['upload_data']['file_name'];
                    }
        unset($config);
        $this->image_lib->clear();
    
        }
    

    【讨论】:

    • 谢谢.. 但我看不到任何文件上传错误。
    • 只需返回 $this->upload->display_errors();在模型函数中查看错误或使用 print_r($this->upload->display_errors());die;在模型功能中由您决定
    • 谢谢@Daniel
    • 永远是我的荣幸 vishal kumar
    【解决方案4】:

    Jquery serialize() 方法无法发布文件数据。

    请使用 jquery 插件来使用 ajax 发布文件数据。如下所示。

    dmuploader.js
    dmuploader.min.js
    

    举个简单的例子click here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-13
      • 2014-12-13
      • 2022-01-22
      • 2017-05-25
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多