Laravel 4中的mime类型验证不起作用 [英] mime type validation in laravel 4 doesn't work

查看:81
本文介绍了Laravel 4中的mime类型验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证laravel中上传文件(mp3文件)的文件大小和mime类型.但是,仅当我上传图片(gif,png)时,验证才开始生效.当我上传大小为100Mb的mkv文件时,验证似乎可以.这是我当前的代码:

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!

推荐答案

尝试将文件规则行更改为:

Try changing the file rules line to:

$file_rules = array('audio_file' => 'size:5242880|mimes:audio/mpeg,audio/mp3,audio/mpeg3');

根据,"audio/mpeg"是mp3文件的正确MIME类型(某些浏览器也使用音频/mpeg3"或音频/mp3").

According to this, 'audio/mpeg' is the correct MIME type for mp3 files (some browsers also use 'audio/mpeg3' or 'audio/mp3').

如果这不起作用,则可以在验证之前获取MIME类型:

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
}

这篇关于Laravel 4中的mime类型验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆