Laravel 文件类型验证无法识别的文件类型

cha*_*lly 1 php mime laravel

我正在尝试像这样验证 Laravel 中的文件类型:

'rules' => ['mimes:pdf,bdoc,asice,png,jpg']
Run Code Online (Sandbox Code Playgroud)

验证适用于pdfpng和,jpg但不适用于bdocasice文件(具有这些扩展名的文件未通过验证)。

我的猜测是,它可能不适用于这些文件类型,因为它们不包含在此处显示的 MIME 类型中: https: //svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime .types

我的这个假设正确吗?如果是这样,我如何验证这些文件类型?

Lui*_*gel 5

您需要为特定文件类型创建自定义验证规则。

在此处查看有关创建自定义验证的文档。https://laravel.com/docs/8.x/validation#custom-validation-rules

更新:添加了一些示例代码。

验证规则

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class AcceptableFileTypesRule implements Rule
{
    protected array $acceptableTypes = [];

    public function __construct(array $acceptableTypes = [])
    {
        $this->acceptableTypes = $acceptableTypes;
    }

    /**
     * @param string $attribute
     * @param \Illuminate\Http\UploadedFile $value
     *
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        return in_array($value->getClientOriginalExtension(), $this->acceptableTypes);
    }

    public function message(): string
    {
        // Change the validation error message here
        return 'The validation error message.';
    }
}

Run Code Online (Sandbox Code Playgroud)

你可以这样使用它

[
   'rules' => ['required', new App\Rules\AcceptableFileTypesRule(['pdf,bdoc,asice,png,jpg'])]
]
Run Code Online (Sandbox Code Playgroud)