0

In laravel5 official documentation i get validation rules here http://laravel.com/docs/5.0/validation#rule-size . For files, size corresponds to the file size in kilobytes. And according to it i make a rules for validation image file:

'property_image'         => 'mimes:jpeg,bmp,png,gif|size:2048'

But its expect exactly 2048K size image. So, I want min, max size or range for validation image. Is there anyway?

1 Answer 正确答案


这里 2048就是2M,如果是 10240就是10M
3
'property_image' => 'mimes:jpeg,bmp,png,gif|max:2048'

btw. there's no jpg mime, image/jpeg is proper mime type.

来自  https://stackoverflow.com/questions/29477339/image-size-validation-in-laravel5



Laravel 5.3 Image Upload with Validation example

 By Hardik Savani |  September 2, 2016 |  | 244974 Viewer |  Category : PHP Laravel



Laravel is very popular PHP framework today and Laravel 5.3 released few days ago. There are several changes and enhancement on Laravel 5.3 version.


So, Today i want to share with you how to image uploading in Laravel 5.3 with validation. If you are beginners then you can do that simply by following few step. Laravel 5.3 provide very simple way to create file uploading with proper validation like max file size 2MB, valid file extension like jpeg,png,jpg,gif or svg etc. So you can easily also implement this on your laravel 5.3 application.


I give you very easy and simple example that way you can understand very well. So you have to just following few step and get output like as bellow preview:


Preview:


Step 1: Add Route

First we have add two route in routes.php file. first one for generate view and second one for post method. so let's add bellow route in your route file.

routes/web.php



Route::get('image-upload','ImageController@imageUpload');

Route::post('image-upload','ImageController@imageUploadPost');



Step 2: Add Controller

Ok, now we need to create ImageController.php file. If you don't have ImageController then you can create new and put bellow code on that file. Make sure you have "images" folder with full permission in your public directory. we will store image in images directory.

app/Http/Controllers/ImageController.php



namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Http\Requests;


class ImageController extends Controller

{


   /**

   * Create view file

   *

   * @return void

   */

   public function imageUpload()

   {

    return view('image-upload');

   }


   /**

   * Manage Post Request

   *

   * @return void

   */

   public function imageUploadPost(Request $request)

   {

    $this->validate($request, [

           'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

       ]);


       $imageName = time().'.'.$request->image->getClientOriginalExtension();

       $request->image->move(public_path('images'), $imageName);


    return back()

    ->with('success','Image Uploaded successfully.')

    ->with('path',$imageName);

   }


}




Step 3: Create Blade File

In At Last we require to create view file for image or file uploading. so you can create image-upload.blade.php and put following code in that file.

resources/views/image-upload.blade.php



<!DOCTYPE html>

<html>

<head>

<title>Laravel 5.3 Image Upload with Validation example</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

</head>

<body>


<div class="container">

<div class="panel panel-primary">

 <div class="panel-heading"><h2>Laravel 5.3 Image Upload with Validation example</h2></div>

 <div class="panel-body">


  @if (count($errors) > 0)

<div class="alert alert-danger">

<strong>Whoops!</strong> There were some problems with your input.<br><br>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif


@if ($message = Session::get('success'))

<div class="alert alert-success alert-block">

<button type="button" class="close" data-dismiss="alert">×</button>

       <strong>{{ $message }}</strong>

</div>

<img src="/images/{{ Session::get('path') }}">

@endif


<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">

{{ csrf_field() }}

<div class="row">

<div class="col-md-12">

<input type="file" name="image" />

</div>

<div class="col-md-12">

<button type="submit" class="btn btn-success">Upload</button>

</div>

</div>

</form>


 </div>

</div>


</div>


</body>

</html>




来自  http://itsolutionstuff.com/post/laravel-53-image-upload-with-validation-exampleexample.html


Laravel 5.3 - image dimension validation rules example

 By Hardik Savani |  September 24, 2016 |  | 45457 Viewer |  Category : Laravel



Laravel 5 provide new image dimensions validation option for image upload. In this validation rules we can set several rules like as listed bellow:

Dimensions Rules:

1)width

2)height

3)min_width

4)min_height

5)max_width

6)max_height

7)ratio


In this Dimensions option through we can set fix width and height, if invalid width and height of image then it will return error. Same way we can set validation min and max height width on your validation.


Few days ago i posted image upload with validation post in Laravel 5.3, you can see here : Laravel 5.3 Image Upload with Validation example.


In this post i used simple validation with mime type and max size like as bellow :



$this->validate($request, [

'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

]);




You can also replace your validation using Dimensions rules like as bellow:

Example 1:



$this->validate($request, [

   'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:width=500,height=500',

]);




Example 2:



$this->validate($request, [

   'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:min_width=350,min_height=600',

]);



Example 3:



$this->validate($request, [

   'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:max_width=350,max_height=600',

]);




Example 4:



$this->validate($request, [

   'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:ratio=3/2',

]);




来自  https://itsolutionstuff.com/post/laravel-53-image-dimension-validation-rules-exampleexample.html



JackD
JackD
Mar 23, 2015
  • Ten Thousand Strong Achievement

image validation

how to validation image based on file type and maximum file size?

i tried this

'image' => 'image:jpg,png|max:5000',

but i got a validation error even i upload a 2mb .png image

deadlockgB
Level 3

What's the error message for the failed rule?

JackD
Level 6

it says "The image must be an image"

JackD
Level 6

but when i tried to make it

'image' => 'required'

it accepts the image, why it is like that?

deadlockgB
Level 3

Ah now I see. You use the image rule incorrect. So this should work:

'image' => 'image|mimes:jpg,png|max:5000',
JackD
Level 6

now im getting two this validation error, i already tried both jpg and png image to upload

The image must be an image.
The image must be a file of type: jpg, png.
deadlockgB
Level 3

This means you are not uploading a .png image to your server. is the file in the

<input type="file" name="image" />

really a .png?

Is the 'image' rule applied to an 'image' field?

JackD
Level 6

yes i tested already a jpg and png file but i got the same validation error message

JackD
Level 6

here is my actual input tag for the file upload

<input type="file" name="image[]">
SachinAgarwal
Level 20

@ci it should be like this

<input type="file" name="image">

it is not a array, so u should not make name as array.

JackD
Level 6

@SachinAgarwal but i need it to be in an array because i have a button to append more input fields for image when clicked

JackD
Level 6

@deadlockgB @SachinAgarwal

<form enctype="multipart/form-data" accept-charset="UTF-8" action="/route-to-post"" method="POST">
<form enctype="multipart/form-data" accept-charset="UTF-8" action="/route-to-post" method="POST">
    <input type="file" name="image[]" />
    <input type="file" name="image[]" /> //this will be added when a add more image button was clicked
</form>
Route::post('route-to-post', function()
{
    $files = \Input::file('files');
    $output = "";
    foreach ($files as $file) {
        $output .= $file->getClientOriginalName();
    }
    return $output;
});
JackD
Level 6

@usman any idea on this bro?

SachinAgarwal
Level 20

@Ci the prob is, when it is an array, you need to specify that its an array. Not sure weather it will work, but give it a try

'image' => 'array|image|mimes:jpg,png|max:5000',
deadlockgB
Level 3

Also if you name the input fields "image[]" you will get them by accessing (the name attribute in the HTML is the accessor for the \input::files() array)

$images = \Input::file('image');

So the first thing you can validate if if $images (so all the images you uploaded in the 'image[]' input fields) is of type array:

$filesArArray = \Validator::make(
    ['images' => $images], // this is your \Input::file('image'); array from above
    ['images' => 'array'] // this is the rule for the array
);

After that you can loop through your images and see if the separat images are to your specification:

foreach($images as $image)
{
     $imagesAreImages = \Validator::make(
         ['image' => $image], // this is the single image instance
         ['image' => 'image|mimes:jpg,png|max:5000'] // this is the rule for a single image
     );
}

I hope you get the idea now

usman
Level 26

@Ci here you go:

  //getting the image array.
  $file = app('request')->file('image');

  //define the basic rule that image should be array.
  $valid = app('validator')->make(compact('file'),['file'=>'required|array']);

  //for each array inside the array define a rule that : image cannot exceed 5000kb and it should be either png or a jpeg.
  $valid->each('file',['mimes:png,jpeg|max:5000']);

  //check your validation as usual here.
  $valid->passes(); //whatever.

Usman.

deadlockgB
Level 3

@usman Great solution!

usman
Level 26
JackD
Level 6

@usman great but im getting this error "Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)" is it a bug?

deadlockgB
Level 3

check your (correct) php.ini file. search for the line ;extension=php_fileinfo.dll and delete the ; at the front. Restart your webserver after that or if you use php-fpm restart the fpm deamon

JackD
Level 6

@deadlockgB yes it is working now but the validation only works on the file format the file size is not being validated.. i tried to change the max from max:5000 to max:1000 and upload a 2MB jpg and it accept it, why it does not check the file size for validation?

JackD
Level 6

i noticed that it is also not being required when i tried to submit empty field for the file even though there is a required in my code

deadlockgB
Level 3

Allright I did some testing. I used a 24kb file named test.jpg and a 5kb file named test.png.

  • rule set 'image|mimes:jpeg,png|max:20': the validator passes the test.png but fails the test.jpg (because of the file size)

  • rule set 'image|mimes:jpeg,png|max:25': both files pass

  • rule set 'image|mimes:jpg,png|max:25': the test.jpg fails (notice the missing e in jpeg)

So in my end the validation works best when the mimes are set to mimes:jpg,jpeg,png and the size is set (as stated in the docs) as kilobytes. Not that the value you pass to max is divided by 1024 so you should propably use multiples of that for megabytes (5MB = 5120).

JackD
Level 6

@deadlockgB yes it works on me now after i restart my xampp and browser

have i done it right in my code? though it is working but i find my code weird because of the two validator that i need to implement haha

       $files =\Input::file('image');
        $filesAreArray = \Validator::make(
            ['image'=>$files],
            ['image'=>'array']
        );

        foreach($files as $file)
        {
            $imagesAreImages = \Validator::make(
                ['image' => $file],
                ['mage' => 'required|image|mimes:jpg,png|max:2000']
            );
        }


      $validator = $this->registrar->validate_profile($request->all());

         if($validator->fails()) {
             
             $this->throwValidationException($request, $validator);
         }

        if($imagesAreImages->fails())
        {
            $this->throwValidationException($request, $imagesAreImages);
        }
deadlockgB
Level 3

you could make it a lot mor readable with @usmans method from the first page (the $valif->each() function)

来自  https://laracasts.com/discuss/channels/general-discussion/image-validation