Reputation:
What Perl module turns a file extension (.txt, .jpeg) into a mime type (text/plain, image/jpeg)?
I want
my $mime = file_to_mime ("some.txt");
# $mime = 'text/plain'
Upvotes: 0
Views: 1309
Reputation: 954
Although the answer by davewood is correct, it does a lot of checks and making things very explicit. MIME::Types
does the right thing out of the box!
There is no need to split the filename to extract the file extension. If you provide a filename with extension, it will extract it by itself. If the text does not have an extension, then it will use that string as the extension.
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";
NOTE: Never rely on the extension only, you might consider File::Type
that introspects the file itself, or a more recent module File::MimeInfo::Magic
.
Upvotes: 5
Reputation: 206
EDIT: The answer by Th.J. is probably better. (https://stackoverflow.com/a/22832209/1702521) but I'll leave mine unedited for completeness sake.
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/ say /;
use MIME::Types;
my $file = "foo.txt";
my $mime_types = MIME::Types->new( only_complete => 1 );
$mime_types->create_type_index;
my ($ext) = $file =~ /\.(.+?)$/;
die "Could not find file extension. (" . $file . ")"
unless defined $ext;
my $content_type = $mime_types->mimeTypeOf($ext);
die "No content-type found for '$ext'"
unless defined $content_type;
say $content_type;
Upvotes: 1