【问题标题】:Laravel file type validation for unrecognised file types无法识别的文件类型的 Laravel 文件类型验证
【发布时间】:2022-01-09 18:19:36
【问题描述】:

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

'rules' => ['mimes:pdf,bdoc,asice,png,jpg']

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

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

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

【问题讨论】:

    标签: php laravel mime


    【解决方案1】:

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

    在此处查看有关创建自定义验证的文档。 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.';
        }
    }
    
    

    你可以这样使用它

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

    【讨论】:

    • 谢谢,正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多