Get the content type of the uploaded file

To get the content type of the uploaded file, use the headers method of the Mojo::Upload class. Use it to get the Mojo::Headers object and call the content_type method.

# Get the content type of the uploaded file
my $content_type = $upload->headers->content_type;

Content type and extension

Describes common image content types and PDF extensions.

PNG

# Extension content type
png image / png

JPEG

# Extension content type
jpeg image / jpeg
jpg image / jpeg

GIF

# Extension content type
gif image / gif

PDF

# Extension content type
pdf application / pdf

Determine the extension from the content type

If you want to save an uploaded file, you may want to create file extensibility, depending on the type of content type. Here is a sample of such logic. Judgment is made using regular expression.

my $content_type ='image / png';
my $ext;

#PNG
if ($content_type = ~ m | \ bimage / png \ b |) {
  $ext ='png';
}
#JPEG
elsif ($content_type = ~ m | \ bimage / jpeg \ b |) {
  $ext ='jpg';
}
#GIF
elsif ($content_type = ~ m | \ bimage / gif \ b |) {
  $ext ='gif';
}
#PDF
elsif ($content_type = ~ m | \ bapplication / pdf \ b |) {
  $ext ='pdf';
}
else {
  #Unexpected content type
}

print "$ext\n";

Associated Information