【问题标题】:Validating Image Uploads验证图片上传
【发布时间】:2017-05-28 18:48:54
【问题描述】:

哟!我正在制作一个附有图片的表单。

表格:

{{ Form::file('attachments[]', array('multiple')) }}

验证:

$this->validate($response, array(
    'attachments' => 'required | mimes:jpeg,jpg,png',
));

我也尝试将“图像”作为验证规则,但每当我使用 jpg 图像发布表单时,我都会收到错误消息:

附件必须是以下类型的文件:jpeg、jpg、png。

使用 Laravel 5.3

【问题讨论】:

    标签: laravel-5


    【解决方案1】:

    由于您定义了attachments[] 的输入名称,附件将是一个数组包含您的文件。如果您只需要上传一个文件,您可能希望将输入名称重命名为attachments,而不使用[](或attachment 在这种情况下更有意义)。如果您需要能够上传多个,您可以在Request-extending 类中构建一个迭代器,该迭代器返回一组规则,涵盖attachments[] 中的每个条目

    protected function attachments()
    {
        $rules          = [];
        $postedValues   = $this->request->get('attachments');
    
        if(null == $postedValues) {
            return $rules;
        }
    
        // Let's create some rules!
        foreach($postedValues as $index => $value) {
            $rules["attachments.$index"] = 'required|mimes:jpeg,jpg,png';
        }
        /* Let's imagine we've uploaded 2 images. $rules would look like this:
            [
                'attachments.0' => 'required|mimes:jpeg,jpg,png',
                'attachments.1' => 'required|mimes:jpeg,jpg,png'
            ];
        */
    
        return $rules;
    }
    

    然后,您只需在 rules() 中调用该函数,即可将从 attachments 返回的数组与您可能希望为该请求指定的任何其他规则合并:

    public function rules()
    {
        return array_merge($this->attachments(), [
           // Create any additional rules for your request here... 
        ]);
    }
    

    如果您的表单还没有专门的Request-扩展类,您可以使用 artisan cli 输入 create onephp artisan make:request MyRequestName。将在app\Http\Requests 中创建一个新的请求类。那是您将上面的代码放入的文件。接下来,您可以在控制器端点的函数签名中使用 typehint 这个类:

    public function myControllerEndpoint(MyRequestName $request)
    {
        // Do your logic... (if your code gets here, all rules inside MyRequestName are met, yay!)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2016-05-26
      • 1970-01-01
      • 2015-03-13
      • 2017-03-26
      • 2018-12-15
      相关资源
      最近更新 更多