";您没有选择要上载的文件";使用ajax上传图像时出现此错误


"You did not select a file to upload. " get this error while uploading image using ajax

我正在使用CodeIgniter和jQuery ajax。我想用ajax上传图片。但它显示了类似You did not select a file to upload. 的错误

在这里,我写了jQuery:

jQuery(document).on('submit', '#signup_form', function()
		{
			//debugger;
			var data = jQuery(this).serialize();
			jQuery.ajax({
				type : 'POST',
				url  : '<?php echo base_url()."front/ajax_register"; ?>',
				data : data,
				success :  function(data)
				{
					jQuery(".result").html(data);
				}
			});
			return false;
		});
<form id="signup_form" method="post" enctype="multipart/form-data">
   <div class="row">
        <div class="col-md-3">Upload Photo</div>
        <div class="col-md-4">
            <input type="file" name="pic" accept="image/*">
        </div>
   </div>
   <div class="row">
        <button type="submit" class="btn btn-default">Submit</button>       
   </div>
</form>

我的函数是这样的:

function ajax_register()
{
    if($this->input->post())
    {
        $this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
        $this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
        if($this->form_validation->run() == true)
        {
            $img = "";
            $config['upload_path'] = './uploads/user/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $this->upload->initialize($config);
            if ( ! $this->upload->do_upload('pic'))
            {   
                $data['error'] = array('error' => $this->upload->display_errors());
                print_r($data['error']);exit;
                $data['flash_message'] = "Record is not inserted";
            }
            else
            {
                $upload = $this->upload->data();
                //print_r($upload);exit;
                $data = array(
                        'ip_address'            =>$this->input->ip_address(),
                        'first_name'            =>$this->input->post('firstname'),
                        'last_name'             =>$this->input->post('lastname'),
                        'phone'                 =>$this->input->post('phone'),
                        'email'                 =>$this->input->post('email'),
                        'group_id'              =>$this->input->post('role'),
                        'password'              =>$this->input->post('password'),
                        'image'                 =>$upload['file_name'],
                        'date_of_registration'  =>date('Y-m-d')
                    );
                print_r($data);exit;
                $user_id = $this->admin_model->insert_user($data);
                $user_group = array(
                        'user_id'   => $user_id,
                        'group_id'  => $this->input->post('role')
                    );
                $this->admin_model->insert_group_user($user_group);
                echo "<p style='color:red;'>You are successfully registerd.</p>";                
            }
        }
        else
        {
            echo "<p style='color:red;'>".validation_errors()."</p>";
        }
    }
}

那么如何解决这个问题呢?我的代码中应该更改什么?

正如我所说,问题可能在于发送到后端的数据。如果您想提交带有输入文件的AJAX,请使用FormData。

试试这个:

jQuery(document).on('submit', '#signup_form', function()
{
    //debugger;
    var data = new FormData($('#signup_form')[0]);
    jQuery.ajax({
        type : 'POST',
        url  : '<?php echo base_url()."front/ajax_register"; ?>',
        data : data,
        processData: false,
        contentType: false,
        success :  function(data)
        {
            jQuery(".result").html(data);
        }
    });
    return false;
});

试试这个:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

Php:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }
?>

这将上载文件。

p.S.:根据CI方法更改代码。

var data = jQuery(this).serialize();

thisdocument