laravel 4 中的 mime 类型验证不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22981739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mime type validation in laravel 4 doesn't work
提问by user225269
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:
我正在尝试验证 Laravel 中上传文件(mp3 文件)的文件大小和 MIME 类型。但是验证似乎只在我上传图像(gif、png)时才开始。当我上传大小为 100Mb 的 mkv 文件时,验证似乎没问题。这是我当前的代码:
$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!
任何想法我的代码有什么问题?提前致谢!
回答by kajetons
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').
根据该“音频/ MPEG”是正确的MIME类型为MP3文件(有些浏览器也使用“音频/ MPEG3”或“音频/ MP3”)。
If that doesn't work, you could get the MIME type before validation:
如果这不起作用,您可以在验证之前获取 MIME 类型:
$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
}
回答by kovpack
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
所选答案不起作用:$file->getMimeType()
返回不可预测的结果。文件,如.css
,.js
,.po
,.xls
以及更多获得text/plain
MIME类型。所以我在那里发布了我的解决方案https://stackoverflow.com/a/26299430/1331510