laravel image validation image intervention

2019-08-15 07:30发布

问题:

I have a file upload in my vue js component which sends base64 in server

methods: {
    onFileChange(e) {
        console.log(e.target.files[0]);
        let fileReader = new FileReader();
        fileReader.readAsDataURL(e.target.files[0]);
        fileReader.onload = (e) => {
        this.product.cover_image = e.target.result
       };
   },

<div class="form-group">
    <label for="exampleInputFile">Upload Image of Product</label>
    <input type="file" ref="fileupload" v-on:change="onFileChange" id="exampleInputFile">
</div>

and in my controller in laravel im using image intervention to save the image via Image::make

public function store(Request $request){
   $this->validate($request, [
       'name' => 'required|max:255',
       'price' => 'required|numeric',
       ]);
   $image = $request->get('cover_image');
   $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
   Image::make($request->get('cover_image'))->save(public_path('cover_images/').$name);
   $product = new Product;
   $product->name = $request->input('name');
   $product->description = $request->input('description');
   $product->price = $request->input('price');
   $product->cover_image = $name;
   if($product->save()) {
          return new ProductsResource($product);
     }
  }

how can i validate the image before saving? it is in base64 i dont know how to validate it on laravel.

回答1:

Inside the AppServiceProvider i put the custom validation

public function boot()
{
    Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
        $type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
        if (in_array($type, $parameters)) {
            return true;
        }
        return false;
    });

    Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
        return str_replace(':values',join(",",$parameters),$message);
    });
}

and on the validation.php i put the

'image64' => 'The :attribute must be a file of type: :values.',

now i can use this in validating the request

'image' => 'required|image64:jpeg,jpg,png'

credits to https://medium.com/@jagadeshanh/image-upload-and-validation-using-laravel-and-vuejs-e71e0f094fbb



回答2:

If you only want to validate uploaded file to be an image type:

$this->validate($request, [
   'name' => 'required|max:255',
   'price' => 'required|numeric',
   'cover_image' => 'required|image'
]);

The file under validation must be an image (jpeg, png, bmp, gif, or svg)

Laravel 5.6 image validation rule