在Laravel 5中,如何从扩展中获取MIME类型?如果有一种方法可以将扩展数组转换为模拟数组,那就更好了。
例如,如何将array('doc', 'xls')
转换为array('application/msword', 'application/vnd.ms-excel')
?
当"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
$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);
从扩展数组中获取MIME类型数组:
$mimetypes = new 'GuzzleHttp'Mimetypes;
$mimes = [];
foreach ($extensions as $extension) {
$mimes[] = $mimetypes->fromExtension($extension);
}
MimeType::from('koala_transparent.png')
return"images/png"
首先,您需要下载这个公共域文件: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");
输出:
应用程序/msword
转换阵列:
$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);
我使用
https://github.com/ralouphie/mimey
它可以通过扩展名提供mimetype,而不需要现有文件