Limit number of files that can be uploaded

前端 未结 2 1332
礼貌的吻别
礼貌的吻别 2021-01-15 18:31

How can I limit the number of files that can be uploaded?

The max validation seems to apply to the size of the image (in kilobytes). How can I make a va

相关标签:
2条回答
  • 2021-01-15 19:06

    In laravel, there is no built-in validation rule for that. But you can create custom-validation rule to handle this.

    Here is a simple custom-validation rule for it.

    Create customValidator.php in app/ directory.

    Validator::extend('upload_count', function($attribute, $value, $parameters)
    {   
        $files = Input::file($parameters[0]);
    
        return (count($files) <= $parameters[1]) ? true : false;
    });
    

    Don't forget to add it to app/start/global.php

    require app_path().'/customValidator.php';
    

    In your validation setting,

    $messages = array(
        'upload_count' => 'The :attribute field cannot be more than 3.',
    );
    
    $validator = Validator::make(
        Input::all(),
        array('file' => array('upload_count:file,3')), // first param is field name and second is max count
        $messages
    );
    
    if ($validator->fails()) {
         // show validation error
    }
    

    Hope it will be useful for you.

    0 讨论(0)
  • 2021-01-15 19:11

    How I did in laravel 7.x

    Create a new form request class with the following command

    php artisan make:request UploadImageRequest

    use Illuminate\Foundation\Http\FormRequest;
    use App\Http\Requests\BaseFormRequest;
    
    class UploadImageRequest extends BaseFormRequest
    {
    public function authorize()
    {
      return true;
    }
    
    public function rules()
    {
      return [
        'coverImage.*' => 'image|mimes:png,jpg,jpeg,gif,svg|max:2048',
        'coverImage' => 'max:5',
      ];
    } 
    
    public function messages() {
      return [
        'coverImage.*.max' => 'Image size should be less than 2mb',
        'coverImage.*.mimes' => 'Only jpeg, png, bmp,tiff files are allowed.',
        'coverImage.max' => 'Only 5 images are allowed'
      ];
    }
    

    in View.blade.php

    <input type="file" id="coverImage" name="coverImage[]"
                            class="form-control-file @error('coverImage') is-invalid @enderror" multiple>                        
    @error('coverImage')
     <span class="text-danger">{{ $message }}</span>
    @enderror
    

    in controller

    public function store(UploadImageRequest $request)
    {
      //code
    }
    
    0 讨论(0)
提交回复
热议问题