什么Perl模块将文件扩展名(.txt,.jpeg)转换为mime类型(text/plain,image/jpeg)?
我想要
my $mime = file_to_mime ("some.txt");
# $mime = 'text/plain'
Run Code Online (Sandbox Code Playgroud)
虽然davewood的答案是正确的,但它会做很多检查并使事情变得非常明确.MIME::Types开箱即用的东西!
无需拆分文件名即可解压缩文件扩展名.如果您提供带扩展名的文件名,它将自行提取.如果文本没有扩展名,那么它将使用该字符串作为扩展名.
use strict;
use warnings;
use MIME::Types; # by Mark Overmeer
my $filename = "some.txt";
my $MIME_Types = MIME::Types->new;
my $mimetype = $MIME_Types->mimeTypeOf($filename)
or die "Could not find MIME type for '$filename'";
print "Filename '$filename' of MIME type '$mimetype'\n";
Run Code Online (Sandbox Code Playgroud)
注意:永远不要仅依赖于扩展,您可能会考虑File::Type内省文件本身或更新的模块File::MimeInfo::Magic.