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!

pkaeding
  • 36,513
  • 30
  • 103
  • 141

2 Answers2

5

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
  • 96,171
  • 6
  • 121
  • 214
1

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
  • 11,957
  • 7
  • 46
  • 68
  • 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 Dec 16 '08 at 14:47