Reputation: 4173
I learned it is required to modify the values in php.ini
in order to set the limitation for uploading files. However, I'm in a situation where I can't touch php.ini
.
Let me explain the problem briefly.
<input type="file" name="thumbnail" accept="image/*">
I'm trying to get the thumbnail
and get it in a controller.
if($this->request->hasFile('thumbnail')){
$file = $this->request->file('thumbnail');
//Other tasks
}
If the file size is over a certain point, I'd like to prevent it and show a warning. However, apparently, if the uploaded file is over the limit, request->hasFile()
returns false even though it's actually true.
(I saw that by dd()
)
It's probably impossible to catch this type of error by hasFile()
, since it simply doesn't catch it.
Any advice would be appreciated.
Upvotes: 1
Views: 387
Reputation: 4795
Use validation rule max
$validator = Validator::make($request->all(), [
...
'thumbnail' => 'max:30000', // kilobytes
...
]);
Upvotes: 2
Reputation: 1616
Fist of all, make sure that your form uses multipart/form-data
enctype.
<form action="/upload-image" method="post" enctype="multipart/form-data">
<input type="file" name="thumbnail" accept="image/*">
<input type="submit">
</form>
To get the file size you can use getClientSize()
function of UploadedFile object.
So to limit the size and show a warning, you can do something like that:
if ($this->request->file('thumbnail')->getClientSize() > 5){
return redirect()->back()->withErrors(['thumbnail', 'File is too big. Limit is 5MB.']);
}
Then in the view print the error.
Upvotes: 1
Reputation: 1101
Have you checked the validation rules?
Validating Files
Rule:
size:value
The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.
Upvotes: 0