【问题标题】:Image validation not working If using ajaxForm图像验证不起作用如果使用 ajaxForm
【发布时间】:2015-06-01 23:53:54
【问题描述】:

我尝试使用谷歌搜索并看到此论坛上发布的其他问题,但找不到任何解决我的问题的方法。我正在使用 Jquery ajaxForm 方法提交表单。我的表单中也包含一个 file 字段,可用于上传图片。我已经在我的模型中定义了验证。但问题是即使我上传了正确的jpg 文件,我仍然收到错误消息

Argument 1 passed to Illuminate\\Validation\\Factory::make() must be of the type array, object given.

Javascript 代码

$('#create_form').ajaxForm({
    dataType:'JSON',
    success: function(response){
        alert(response);    
    } 
}).submit();

控制器代码

if ($file = Input::file('picture')) {
    $validator = Validator::make($file, User::$file_rules);

    if ($validator->fails()) {
        $messages = $validator->messages();
        foreach ($messages->all(':message') as $message) {
            echo $message; exit;
        }
        return Response::json(array('message'=>$response, 'status'=>'failure'));
    } else {
        // do rest 
    }
}

型号代码

public static $file_rules = array(
    'picture' => 'required|max:2048|mimes:jpeg,jpg,bmp,png,gif'
);

POST 请求

我知道我在模型中定义的验证需要一个数组。但是通过在验证器中传递$file,传递了一个对象。然后我将代码更改为:

$validator = Validator::make(array('picture' => $file->getClientOriginalName()), User::$file_rules);

现在我收到错误:

The picture must be a file of type: jpg, JPEG, png,gif.

【问题讨论】:

    标签: validation file-upload laravel-4 ajaxform


    【解决方案1】:

    试试这样的规则。

    $rules = array(
     'picture' => 'image|mimes:jpeg,jpg,bmp,png,gif'
    );
    

    或尝试删除“哑剧”

    【讨论】:

      【解决方案2】:

      问题是您直接将文件对象传递给验证。 Validator::make() 方法将所有四个参数作为数组。此外,您需要将整个文件对象作为值传递,以便Validator 可以验证 mime 类型、大小等。这就是您的代码应该是这样的原因。

      $input = array('picture' => Input::file('picture'));
      $validator = Validator::make($input, User::$file_rules);
      
      if ($validator->fails()) {
          $messages = $validator->messages();
          foreach ($messages->all(':message') as $message) {
              echo $message; exit;
          }
          return Response::json(array('message'=>$response, 'status'=>'failure'));
      } else {
          // do rest 
      }
      

      希望对你有用。

      【讨论】:

      • 替换您的代码后,我得到了文件扩展名的正确错误,但是当我上传一个大小超过允许大小 200kb 的大文件时,我收到错误“图片字段是必需的”。我不明白为什么会出现这个错误。
      • 我用邮递员测试时没有问题。让我知道解决它的细节。
      • 我在我的问题中更新了我的模型代码。因此,当我尝试上传大小大于 2MB 的图像时,我收到错误消息“需要图片字段”。增加 max_upload_size 的大小可能会有所帮助吗?
      • 是的。发生这种情况是因为这个问题。 github.com/laravel/framework/issues/2433 请增加post_max_sizeupload_max_filesize 来解决您的问题。
      猜你喜欢
      • 2012-09-05
      • 2015-07-17
      • 2015-08-30
      • 2018-06-23
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2016-03-10
      相关资源
      最近更新 更多