codeigniter通过ajax发送输入文件信息

时间:2015-02-03 15:13:55

标签: ajax codeigniter upload

我有一个包含4个字段的表单:标题,价格,图片和类别。

提交后,它会将3个字符串插入数据库并上传图像,或返回错误。一切正常。

但是,现在我想通过ajax完成它。

它适用于标题,价格和类别字段,但如何传递文件字段所需的信息,以便codeigniter可以上传它?

现在它一直说“你没有选择要上传的文件。”

我的控制器:

function add_new_product_ajax() 
    {
        // make sure it's the admin, else redirect
        if ( ! $this->session->userdata('is_admin') ) {
            redirect('admin/login'); 
            exit();
        }

        // get product name
        $pn = $this->input->post('product_title');

        // get price 
        $p = $this->input->post('price');

        // get category id 
        $cid = $this->input->post('categories');

        // upload config
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        $config['overwrite']  = TRUE;

        // load form validation
        $this->load->library('form_validation');

        // validate fields
        $this->form_validation->set_rules('product_title', 'Product Name', 'trim|required|is_unique[products.name]');
        $this->form_validation->set_rules('price', 'Price', 'trim|required|callback_check_price');
        $this->form_validation->set_rules('categories', 'Product\'s Category', 'required');

         // if validation failed
        if ($this->form_validation->run($this) == FALSE) 
        {   
            // dummy var
            $data['dummy'] = '';

            // load categories module to make a select list
            $this->load->module('categories/categories');
            $data['options'] = $this->categories->categories_select();

            // load the view        
            $this->load->view('new_product_view', $data);        
        }
        else // validation passed
        {
            // do upload
            $this->load->library('upload', $config);
            $field_name = "userfile";
            // $this->upload->do_upload($field_name);

            // try to upload 
            if ( ! $this->upload->do_upload()) {

                $data['error'] = $this->upload->display_errors();

                // load categories module to make a select list
                $this->load->module('categories/categories');
                $data['options'] = $this->categories->categories_select();

                // load the view        
                $this->load->view('new_product_view', $data);        

            } 
            else // upload successful, insert data into table 
            {
                // insert product data 
                $this->mdl_products->add_product($pn, $p, $cid);

                // success msg
                $data['msg'] = '<div class=successmsg>The product has been added!</div>'; 

                // load categories module to make a select list
                $this->load->module('categories/categories');
                $data['options'] = $this->categories->categories_select();

                // load the view        
                $this->load->view('new_product_view', $data);        
            }

        }

    }

我的ajax(缺少文件值参数):

$('body').on('click', 'a.submitnewprod', function(e) {
        e.preventDefault();
        // alert('code');return;

        // get product title 
        var pt = $('#product_title').val();

        // get product price 
        var pp = $('#price').val();

        // get category id 
        var cid = $('#categories').val();

        // get userfile ???????
        var uf = $('#uploadImage').val();

        $.ajax({
            type: "POST",
            url: site + "admin/add-new-product-ajax",
            data: { 
                product_title:pt,
                price: pp,
                categories: cid
            },

            beforeSend: function() {
                 $('#ajaximg img').addClass('act');
            },

            success: function(data) {
                // $('.results').html(data);
                $('#ajax').html(data);
            },

            complete: function() {
                 $('#ajaximg img').removeClass('act');
            }

        });


    });

我的视图文件中的文件html:

<input id="uploadImage" type="file" name="userfile" size="20" onchange="PreviewImage();" />

我需要在data参数内传递我的ajax调用,以便上传可以正常工作?

1 个答案:

答案 0 :(得分:0)

在您的PHP中,它与您发布$ _FILE字段的方式无关。而不是抓取单个表单字段尝试使用jQuery的表单序列化函数并将帖子声明为multipart/form-data。有很多关于如何在SO上实现这一点的例子,但看起来应该有点......

       var myData = $('#your_form').serialize(); 
       $.ajax({
            type: "POST", 
            contentType:attr( "enctype", "multipart/form-data" ),
            url: " URL Goes Here ",  
            data: myData
            ...