在Laravel 5中,我该如何从扩展名获取MIME类型?如果有一种方法可以将扩展名数组转换为MIME类型数组,那就更好了。
例如,如何将
例如,如何将
array('doc', 'xls')
转换为array('application/msword', 'application/vnd.ms-excel')
?当在你的composer.json文件中添加了 "guzzlehttp/guzzle": "~5.3|~6.0" 后,您可以使用以下内容:
$mimetype = \GuzzleHttp\Psr7\mimetype_from_filename('foo.doc');
$mimetype = \GuzzleHttp\Psr7\mimetype_from_extension('doc');
@deprecated mimetype_from_filename 将在guzzlehttp/psr7:2.0中被删除。请改用MimeType :: fromFilename。
- raspberry367在L5领域中,无疑是最好的选择:
\File::mimeType('physical/path/to/file.ext');
$request->file->getMimeType()
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg'
'mp3'=>'required|mimetypes:audio/mpeg'
]);
您可以从上述代码中获取文件类型,然后将其设置为mimetypes,就像设置mp3一样。
Guzzle是Laravel 5默认包含的,这个库里有mime类型列表和fromExtension()
方法,它们正好可以做到我们需要的。
因此,要获取单个扩展名的MIME类型:
$mimetypes = new \GuzzleHttp\Mimetypes;
$mime = $mimetypes->fromExtension($extension);
$mimetypes = new \GuzzleHttp\Mimetypes;
$mimes = [];
foreach ($extensions as $extension) {
$mimes[] = $mimetypes->fromExtension($extension);
}
GuzzleHttp\Mimetypes
已经被移动到 GuzzleHttp\Psr7\mimetype_from_extension
函数中,并且新增了 GuzzleHttp\Psr7\mimetype_from_filename
函数。 - BenMimeType::from('koala_transparent.png')
返回 "image/png"
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");
输出:
应用程序/微软字体
将数组转换为:
$myArray = array('doc', 'xls');
foreach($myArray as $key => $value){
$myArray[$key] = getMIME($value);
}
自PSR7 API 2.0版本以来,mimetype_from_filename
被MimeType::fromFilename
替换。
在Laravel 8.x中,这对我有效。
$mimeType = \GuzzleHttp\Psr7\MimeType::fromFilename($filename);