Reputation: 10893
I'm trying to validate the file size and the mime type of an uploaded file (mp3 file) in laravel. But the validation only seem to kick in when I upload an image (gif, png). When I upload an mkv file with a size of 100Mb the validation seems to be ok with it. Here's my current code:
$file = Input::file('audio_file');
$file_rules = array('audio_file' => 'size:5242880|mimes:mp3'); //also tried mpeg
$file_validator = Validator::make(Input::file(), $file_rules);
if($file_validator->fails()){
//return validation errors
}else{
//always goes here and succeeds
}
Any ideas what's wrong with my code? Thanks in advance!
Upvotes: 1
Views: 6539
Reputation: 5045
The selected answer does not work: $file->getMimeType()
returns unpredictable results. Files like .css
, .js
, .po
, .xls
and much more get text/plain
mime type. So I've posted my solution there https://stackoverflow.com/a/26299430/1331510
Upvotes: 0
Reputation: 4580
Try changing the file rules line to:
$file_rules = array('audio_file' => 'size:5242880|mimes:audio/mpeg,audio/mp3,audio/mpeg3');
According to this, 'audio/mpeg' is the correct MIME type for mp3 files (some browsers also use 'audio/mpeg3' or 'audio/mp3').
If that doesn't work, you could get the MIME type before validation:
$file = Input::file('audio_file');
$mimeType = $file->getMimeType();
$supportedTypes = ['audio/mpeg', 'audio/mpeg3', 'audio/mp3'];
if (in_array($mimeType, $supportedTypes)) {
// validate or simply check the file size here
} else {
// do some other stuff
}
Upvotes: 5