0

I have an image uploader on my Vue app that takes multiple files. I want to ensure they are images and of a certain size and if not, obviously don't upload the files and have the frontend display the error. Right now, the route it hits in the controller loos like this:

   public function uploadAssets(UploadAssetsFormRequest $request)
    {
        if ($request->hasFile('file')) {
            $files = $request->file('file');
            $stack = [];
            foreach ($files as $file) {
                $fileName = Storage::put('/check/', file_get_contents($file->getRealPath()), ['visibility' => 'public']);
                array_push($stack, $fileName);
            }
            return response()->json($stack);
        }
    }

My Form Request is below and has the validation but I don't know how to apply that in the controller.

UploadAssetsFormRequest

<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class UploadAssetsFormRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'files.*' => 'required|image|max:1000',
        ];
    }

    public function messages()
    {
        return [
            'files.*.max'   => 'The image is too large',
            'files.*.image' => 'Only image files are allowed.',
        ];
    }
}
burtonLowel
  • 734
  • 7
  • 17

3 Answers3

0

You need to check files extension :

$extension = $file->extension();
$allowed_file_types = ['jpg','png','gif'];
if (in_array($extension, $allowed_file_types)){
//do upload
}else{
Continue;
}

for file sizes check this thread

Siba Al
  • 357
  • 1
  • 14
0

You can use laravel image validation

$this->validate ($input, [
    'files.*.image' => 'image|max:200',
]):

Note: max(size) is in Kilobytes

You can also use dimension rule

$this->validate ($input, [
    'files.*.image' => 'dimensions:min_width=100,min_height=200'
]):

Laravel Image Validation

Laravel Image Dimensions Validation

Manvir Singh
  • 431
  • 4
  • 6
0

You can set the following rule in your validation -

 'file' => 'required|max:100|mimes:jpg,png,bmp' // 100kb, mimes must have image extensions
sn n
  • 319
  • 1
  • 5
  • 19