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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:20:32  来源:igfitidea点击:

mime type validation in laravel 4 doesn't work

phpvalidationlaravellaravel-4mime-types

提问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, .xlsand much more get text/plainmime type. So I've posted my solution there https://stackoverflow.com/a/26299430/1331510

所选答案不起作用:$file->getMimeType()返回不可预测的结果。文件,如.css.js.po.xls以及更多获得text/plainMIME类型。所以我在那里发布了我的解决方案https://stackoverflow.com/a/26299430/1331510