Search code examples
perlcgi-application

How do you get the content type of an uploaded file using CGI::Application?


I am trying to process an uploaded file in a Perl program, using CGI::Application. I need to get the content type of the uploaded file. From what I read, the following should work, but it doesn't for me:

my $filename = $q->param("file");
my $contenttype = $q->uploadInfo($filename)->{'Content-Type'};

As it turns out, $q->uploadInfo($filename) returns undef. So does $q->uploadInfo("file").

Any ideas?

Thanks!


Solution

  • You trust whatever did the upload to give you a good content type? I just save the uploaded file to disk and do:

    chomp(my $mime_type = qx!file -i $uploaded!);
    $mime_type =~ s/^.*?: //;
    $mime_type =~ s/;.*//;
    

    though you could use File::Type, File::MMagic, or File::MimeInfo instead.