Laravel 图像验证

Posted

技术标签:

【中文标题】Laravel 图像验证【英文标题】:Laravel Image Validation 【发布时间】:2022-01-22 11:43:08 【问题描述】:

我正在编写一个 vue 组件,用户可以使用 Laravel 的内置 image validation 在后端上传我想要验证的个人资料图片。我使用带有以下键值对的 JSON 对象的 axios post 调用。

当我去后端时,我通过自定义 Laravel 请求发送它,并在其上放置以下验证规则。

<?php

namespace App\Http\Requests;

use App\Department;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class ChangePersonalInfo extends FormRequest

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    
        if(auth()->user()) return true;
        else return false;
    

    /**
     * Convert certain request parameters before validation
     *
     * @return void
     */
    protected function prepareForValidation()
    
      $this->merge([
        'assigned_states' => explode(',', $this->assigned_states),
        'customer_price_level' => json_encode($this->customer_price_level),
        'customer_price_list' => json_encode($this->customer_price_list),
        'customer_type' => json_encode($this->customer_type),
        'email_notifications' => filter_var($this->email_notifications, FILTER_VALIDATE_BOOLEAN),
        'employee' => filter_var($this->employee, FILTER_VALIDATE_BOOLEAN),
        'read_notification_terms' => filter_var($this->read_notification_terms, FILTER_VALIDATE_BOOLEAN),
        'reviewed' => filter_var($this->reviewed, FILTER_VALIDATE_BOOLEAN),
        'text_notifications' => filter_var($this->text_notifications, FILTER_VALIDATE_BOOLEAN),
        'verified' => filter_var($this->verified, FILTER_VALIDATE_BOOLEAN),
        'termsCode' => json_encode($this->termsCode)
      ]);
    

    /**
     * Get the validation rules that apply to the request.
     * 
     * @return array
     */
    public function rules()
    
      $departments = Department::select(['department_name'])->pluck('department_name')->toArray();

      return [
          'api_token' => 'string|alpha_num',
          'assigned_states' => 'array|nullable',
          'assigned_states_description' => 'string|nullable',
          'avatar_file' => 'string|nullable',
          'bc_details' => 'string|json|nullable',
          'bc_guid' => 'string|nullable',
          'company_address_id' => 'numeric|integer|nullable',
          'company_name' => 'string|nullable',
          'company_website' => 'string|nullable',
          'created_at' => 'string|nullable',
          'customer_price_level' => 'json',
          'customer_price_list' => 'json',
          'customer_type' => 'json',
          'customer_price_level.id' => 'numeric|integer',
          'customer_price_list.id' => 'numeric|integer',
          'customer_type.id' => 'numeric|integer',
          'department' => ['string', 'nullable', Rule::in($departments)],
          'email' => 'required|email',
          'email_notifications' => 'boolean',
          'employee' => 'boolean',
          'first_name' => 'string|nullable|max:30',
          'id' => 'string|integer|alpha_num',
          'imageExtension' => 'string|nullable',
          'imageFile' => 'sometimes|nullable|image|max:2048',
          'last_name' => 'string|nullable|max:30',
          'marketing_preferences' => 'string|nullable',
          'notes' => 'string|nullable',
          'price_level_id' => 'required|numeric|integer',
          'price_list_id' => 'numeric|integer|nullable',
          'primary_address_id' => 'numeric|integer|nullable',
          'pimary_billing_address' => 'numeric|integer|nullable',
          'primary_phone_number_id' => 'numeric|integer|nullable',
          'read_notification_terms' => 'boolean',
          'reviewed' => 'boolean',
          'statusName' => 'string',
          'status_id' => 'numeric|integer|nullable',
          'termsCode' => 'json',
          'termsCode.id' => 'numeric|integer',
          'terms_code_id' => 'numeric|integer|required',
          'text_notifications' => 'boolean',
          'timezone' => 'timezone',
          'title' => 'string|nullable',
          'type_id' => 'required|numeric|integer',
          'updated_at' => 'string|nullable',
          'username' => 'string|nullable',
          'verificationStatus' => 'string',
          'verification_token' => 'string|nullable',
          'verified' => 'boolean'
      ];
  

我收到一条 500 错误消息。

"message":"The given data was invalid.","errors":"imageFile":["The image file must be an image."]

谁能帮我知道为什么它在前端看起来是一个图像文件但无法满足后端验证?

【问题讨论】:

我可以看看你的 laravel 完整代码吗? 看这个问题是否解决你的问题:***.com/questions/61817409/… 【参考方案1】:

检查这个格式

  'imageFile' => 'required|file|max:512|mimes:jpg,png,jpeg'

【讨论】:

【参考方案2】:

你可以试试这个

'image' => 'required|file|image|max:2048'

【讨论】:

【参考方案3】:

我使用FormData 来完成这项工作。之后使用基本的 axios 发布请求就相当简单了。我将添加我使用的最终代码。此 javascript 代码能够将图像正确发送到后端,该图像已在 Laravel 中作为图像进行验证。

let formData = new FormData();
Object.keys(this.form).forEach(key => 
 formData.append(key, this.form[key]);
);
formData.append('imageFile', this.imageFile);

axios(
  method: 'POST',
  url: this.routes.save,
  data: formData
)

【讨论】:

以上是关于Laravel 图像验证的主要内容,如果未能解决你的问题,请参考以下文章

Laravel5 中的图像大小验证

Laravel 5.4:如何验证图像大小?

Laravel 5.5 - 图像验证不起作用

Laravel 5 - 图像验证不起作用

如何修复“文件上传失败。”使用任何图像上传验证时出错 - Laravel 5.7

Laravel 8 我无法验证图像类型