views:

128

answers:

2

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!

+4  A: 

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.

ysth
+1  A: 

Are you checking for anything that might have gone wrong?

I got that exact code to work just fine, but looking at it, it's wrapped in a test for $filename being undef and also for anything in $cgi->cgi_error(). My memories are a bit dim but there must have been a reason for that...

AmbroseChapel
I do know that $filename is not undef, since I am printing that out in a log statement before I try to read the mime type. I didn't check cgi_error(), but I will try that. In any case, File::Type worked well for me, and I like that it doesn't rely on the client to provide the type.
pkaeding