Laravel 5.3, check if the uploaded file is larger than upload_max_filesize (optional download)

In Laravel 5.3, I try to catch if the downloaded file has a larger file size than upload_max_filesize. Download field is not required.

I tried this method but it does not work

public function checkFile($field) { if (request()->hasFile($field)){ // check if field is present $file = request()->file($field); if (!$file->isValid()){ // now check if it valid return back()->with('error', $file->getErrorMessage()); } } } 

I cannot use only if (!$file->isValid()) because the file field is optional, and I get the Call to a member function isValid() on null field if empty.

So, I have to check if the field is present with if (request()->hasFile($field)) , but this does not work for large files, since dd(request()->hasFile('picture')) returns false

Of course, I can rely on the default messages of Laravel Validator, but I get the dummy The picture failed to upload. that does not give a hint to the user.

+7
php upload laravel
source share
5 answers

Laravel Validation will only work if the size of the uploaded file is less than the limit set in php.ini.

If you try to upload a file that exceeds the limit, PHP will not redirect the request to Laravel and will immediately be an error. Therefore, Laravel cannot do anything in this scenario.

One way to fix this is to set a much larger limit in php.ini and then check the file size in Laravel.

+5
source share

You should consider using the built-in Laravel form request validation system. There is a built-in validation rule that allows you to specify the file size max , you can see the documents here:

https://laravel.com/docs/5.3/validation#rule-max

Your rule will look something like this:

 [ 'video' => 'max:256' ] 

This will fail if the downloaded file is larger than 256 KB.

You mentioned that you didn’t like that Laravel was created in verification error messages. No problems! You can change them in the resources/lang/en/validation.php language file, this is the line you need to change:

https://github.com/laravel/laravel/blob/master/resources/lang/en/validation.php#L51

+4
source share

My previous answer handled the case where the uploaded file was larger than the upload_max_filesize parameter in php.ini . But failed when the file size made the request larger than post_max_size (another php.ini parameter). This case is more difficult to handle, because the inputs ( $_POST global if we are handling simple PHP) are cleared.

I think Middleware is a good place for this “check”:

 public function handle(Request $request, Closure $next) { $post_max_size = ini_get('post_max_size') * 1024 * 1024; $content_length = $request->server('HTTP_CONTENT_LENGTH') ?: $request->server('CONTENT_LENGTH') ?: 0; $response = $next($request); if ($content_length > $post_max_size) { return redirect()->back()->with('errors', collect([trans('validation.max.file', ['max' => 2000])])); } return $response; } 

(As I said, this will not save the input.)

+2
source share

Server-side code (in the controller):

The function below is taken from drupal by meustrus in his answer, and I gave an example here. Start with post_max_size

 // Returns a file size limit in bytes based on the PHP upload_max_filesize // and post_max_size $max_size = parse_size(ini_get('post_max_size')); // If upload_max_size is less, then reduce. Except if upload_max_size is // zero, which indicates no limit. $upload_max = parse_size(ini_get('upload_max_filesize')); if ($upload_max > 0 && $upload_max < $max_size) { $max_size = $upload_max; } //Get max upload file size limit... $file_upload_max_size = $max_size; 

Public function for parsing size

 public function parse_size($size) { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } } 

Set compact to send the value of 'file_upload_max_size' in click

 return view('YOURBLADEPATH',compact('file_upload_max_size')); 

JS Check (In Blade):

 <script type="text/javascript"> document.forms[0].addEventListener('submit', function( evt ) { var file = document.getElementById('file').files[0]; if(file && file.size < '{$file_upload_max_size}') { // 10 MB (this size is in bytes) //Submit form } else { //Prevent default and display error evt.preventDefault(); } }, false); 

+1
source share

The default behavior for Laravel file authentication is to reject the file if the download was not normal for any reason. Validation rules then do not apply, so the max rule cannot help you here. In this case, you clearly want to create a special message for this type of error (the maximum file size is exceeded). I think the Validator class extension is an elegant solution.

 use Illuminate\Http\UploadedFile; use Illuminate\Validation\Validator; class UploadSizeValidator extends Validator { protected function validateAttribute($attribute, $rule) { $value = $this->getValue($attribute); if ($value instanceof UploadedFile && $value->getError() != UPLOAD_ERR_OK) { switch ($value->getError()) { case UPLOAD_ERR_INI_SIZE: return $this->addFailure($attribute, 'max_file_size_exceeded', []); // check additional UPLOAD_ERR_XXX constants if you want to handle other errors } } return parent::validateAttribute($attribute, $rule); } } 

Now, how do you tell the framework to use its validator instead of the standard one? You can set the recognizer function in Validator Factory:

 // do this in a 'boot' method of a ServiceProvider use Illuminate\Support\Facades\Validator; Validator::resolver(function($translator, $data, $rules, $messages, $customAttributes) { return new UploadSizeValidator($translator, $data, $rules, $messages, $customAttributes); }); 

Finally, set the appropriate message for the key 'max_file_size_exceeded' in the validation.php lang file.

-one
source share

All Articles