Laravel 5 - 从文件扩展名获取 MIME 类型

Laravel 5 - get MIME type from file extension

在 Laravel 5 中,如何从扩展中获取 MIME 类型?如果有一种方法可以将扩展数组转换为哑剧数组,那就更好了。

例如如何将 array('doc', 'xls') 转换为 array('application/msword', 'application/vnd.ms-excel')

首先,您需要下载这个 public 域文件:http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

然后使用下面的函数读取文件,得到对应的MIME扩展名类型:

function getMIME($extension) {
    $file = "mime.types";
    $in = fopen($file, "r");
    while (($line = fgets($in)) !== false) {
        if (preg_match("/([a-z]+\/[a-z]+)\s+([a-z\s]*)\b($extension)\b/", $line, $match)) {
            return $match[1];
        }
    }
    fclose($in);
    return "error";
}

echo getMIME("doc");

输出:

application/msword

要转换数组:

$myArray = array('doc', 'xls');

foreach($myArray as $key => $value){
    $myArray[$key] = getMIME($value);
}
此库中的

Guzzle is included in Laravel 5 by default, there's the list of mime typesfromExtension() 方法可以准确地完成所要求的内容。

因此,要获取单个扩展名的 MIME 类型:

$mimetypes = new \GuzzleHttp\Mimetypes;

$mime = $mimetypes->fromExtension($extension);

从扩展数组中获取 MIME 类型数组:

$mimetypes = new \GuzzleHttp\Mimetypes;

$mimes = [];
foreach ($extensions as $extension) {
    $mimes[] = $mimetypes->fromExtension($extension);
}

当 "guzzlehttp/guzzle": "~5.3|~6.0" 在你的 composer.json 中时,你可以使用这个:

$mimetype = \GuzzleHttp\Psr7\mimetype_from_filename('foo.doc');
$mimetype = \GuzzleHttp\Psr7\mimetype_from_extension('doc');

简直是L5中的佼佼者:

\File::mimeType('physical/path/to/file.ext');
MimeType::from('koala_transparent.png')

return "image/png"

我用过

https://github.com/ralouphie/mimey

它可以通过扩展名给出 mimetype 没有现有文件

获取文件 mimetype

$request->file->getMimeType()

验证码

$request->validate([
    'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg'
    'mp3'=>'required|mimetypes:audio/mpeg'
   ]);

你可以从上面的代码中获取文件类型,之后你可以将其设置为 mimetypes 就像为 mp3[=12 设置的那样=]