简体   繁体   中英

Laravel 5.1 file upload validation

I want to upload an image file using

 {!! Form::open(['url'=>'admins']) !!}
  {!! Form::input('file','photo',null,['class'=>'photo_input']) !!} 

Also my validation rules are

 public function rules()
{
    return [
       'username'=>'required|max:127|min:3|unique:users,username,'.$this->username,
       'email'=>'required|max:127|email|min:3|unique:users,email,'.$this->email,
       'password'=>'required|max:127|min:5|confirmed',
       'password_confirmation'=>'required|max:127|min:5|',
       'role'=>'required|max:127|min:5|in:programmer,admin,employee',
       'photo' => 'mimes:jpg,jpeg,bmp,png,gif'
    ];
}

But I get an error

The photo must be a file of type: jpg, jpeg, bmp, png, gif.

Whereas the file extension which I choose is jpg, so what's wrong?

The reason behind is you need to define within your form tag the attribute enctype = "multipart/form-data" . So while using Laravel 5.X Form Facade you need to pass the attribute files => true within your array of form open like as

{!! Form::open(['url'=>'admins','files' => true]) !!}
                              //^^^^^^^^^^^^^^^^ added

Source Docs

This issue is also caused due to uploading large file size then the allowed in the php.ini

Please check

upload_max_filesize

and

post_max_size

in php.ini

You can also validate the Image size by extending the Validator

In Your Controller
Validator::extend('img_upload_size', function($attribute, $value, $parameters)
{
 $file = Request::file($attribute);
 $image_size = $file->getClientSize();
 if( (isset($parameters[0]) && $parameters[0] != 0) && $image_size > $parameters[0]) return false;
 return true;
});


In Validation Rules
 return [
 'username'=>'required|max:127|min:3|unique:users,username,'.$this->username,
    'email'=>'required|max:127|email|min:3|unique:users,email,'.$this->email,
    'password'=>'required|max:127|min:5|confirmed',
    'password_confirmation'=>'required|max:127|min:5|',
    'role'=>'required|max:127|min:5|in:programmer,admin,employee',
 'photo' => 'required|mimes:jpeg,bmp,png|img_upload_size:1000000',//!MB
]

我修复了它,原因是我没有在表单中添加enctype。

{!! Form::open(['url'=>'admins','enctype'=>'multipart/form-data']) !!}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM