PHP - Codeigniter验证使用json


PHP - Codeigniter Validation using json

我有一个字段,每个字段都有一个验证。所有验证都在工作。

但问题是在我的领域,将上传文件。即使我已经放了一个图像文件,它仍然会验证我必须上传一个图像。

我使用sweetalert显示验证错误。

我的控制器

public function saveproducts(){
    $config['upload_path'] = 'uploads/products';   
    $config['allowed_types'] = 'jpg|png|jpeg';
    $config['max_size'] = '2048000';
    $config['overwrite'] = TRUE;
    //$config['file_name'] = $this->input->post('prod_name');
    $this->load->library('upload', $config);
    $this->form_validation->set_rules('userfile', 'Product Image','callback_rulesprodimage');
    if($this->form_validation->run()==FALSE){
        echo json_encode(validation_errors());
    }else{
        $products = array(
            'product_image' => $this->input->post('userfile'),
            'upload_data' => $this->upload->data(),
            );
        $this->CrudModel->insertproductdata($products);
        echo json_encode(1);
    }
}
public function rulesprodimage(){
    if (isset($_FILES['userfile']) && !empty($_FILES['userfile']['name'])){
        if ($this->upload->do_upload('userfile')){
        return true;
        }else{
        $this->form_validation->set_message('rulesprodimage', $this->upload->display_errors());
        return false;
        }
    }else{
      // throw an error because nothing was uploaded
      $this->form_validation->set_message('rulesprodimage', "You must upload an image!");
      return false;
    }
}
<<p> 视图/strong>
<form method="post" enctype="multipart/form-data" id="prod-submit">
<div class="form-group">
<label class="control-label">Product Image <span id="required"> * </span></label>
<input type="file" name="userfile" class="form-control">
</div>
</form>
Javascript

$(document).ready(function(){
$('#prod-submit').on('submit',function(e) { 
$.ajax({
    url: base_url+'adminpage/saveproducts/',
    data:$(this).serialize(),
    type:'POST',
    success:function(data){
      var result = JSON.parse(data); 
        if(result===1){ 
            console.log(result);
            document.location.href = base_url+"adminpage/products/"
        }
        else{
           swal({
                type: 'error',
                html: result,
              }).done();
        }
    },
    error:function(data){
    swal("Oops...", "Something went wrong :(", "error");
    }
  });
  e.preventDefault(); 
});

});

文件不会像那样经过ajax,所以$_FILES为空,CI看不到。使用FormData对象可以传输文件而无需重新加载页面。阅读更多关于这个问题的内容。还要注意浏览器兼容性,因为这个api可以在现代浏览器和ie10+上运行。

我通常用jquery插件这样做。有很多。其中最流行的是https://github.com/blueimp/jQuery-File-Upload,其他例如:http://malsup.com/jquery/form/#file-upload

使用FormData而不是序列化来上传文件,尽管我警告它不适合IE9及以下版本,你可以在这里阅读更多关于FormData的信息。

$(document).ready(function(){
$('#prod-submit').on('submit',function(e) { 
// Create a new FormData with your form selector inside.   
var formdata = new FormData($('form')[0]); 
$.ajax({
    url: base_url+'adminpage/saveproducts/',
    data:formdata,
    type:'POST',
    success:function(data){
      var result = JSON.parse(data); 
        if(result===1){ 
            console.log(result);
            document.location.href = base_url+"adminpage/products/"
        }
        else{
           swal({
                type: 'error',
                html: result,
              }).done();
        }
    },
    error:function(data){
    swal("Oops...", "Something went wrong :(", "error");
    }
  });
  e.preventDefault(); 
});