If you just want to make sure that the file you store has the same suffix as the uploaded file, then you're on the right track.

However, if you need is to identify the type of file uploaded and act on it accordingly, you might be better off using the mime type than the file extension. clients with macs will be pretty loose with the extensions, for example.

with CGI.pm to handle the uploads - you are using CGI.pm to handle the uploads, aren't you? - then it's easy:

my $filename = $query->param('upload_field'); my $type = $query->uploadInfo($filename)->{'Content-Type'};

Which will give you something like 'image/gif' or 'text/html'. You can derive a file suffix from the second part in a fairly reliable way, but you might need to map from /text to .txt and /jpeg to .jpg, and so on.

For images, by the way, you can also get a very reliable indication of the type from the absurdly useful Image::Size module:

use Image::Size; my $filename = $query->param('upload_field'); my ($width, $height, $type) = imgsize($filename);

Which will give you a plain 'gif' or 'jpg' or 'png' or 'swf', but doesn't work for anything else.


In reply to Re: filetype extension query by thpfft
in thread filetype extension query by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.