Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there any way to check the size of a file that's uploaded via CGI before writing it to the server? That way I don't have to write it and then delete it if it's too large. Right now I am using content_length ENV but that would only work for one upload, not two uploads at once.

Replies are listed 'Best First'.
Re: size of file upload
by hesco (Deacon) on Feb 13, 2006 at 03:02 UTC
    You might also consider including lines like the following to protect yourslef ahead of time.

    $CGI::POST_MAX = $pkg_conf::config{'post_max'}; $CGI::DISABLE_UPLOADS = $pkg_conf::config{'disable_uploads'}; $CGI::HEADERS_ONCE = $pkg_conf::config{'headers_once'};
    And in my configuration file, I include:
    # post_max: value of $CGI::POST_MAX post_max = 10240 # disable_uploads: value of $CGI::DISABLE_UPLOADS disable_uploads = 1 # headers_once: value of $CGI::HEADERS_ONCE headers_once = 1
    Though I guess you'd want to set disable_uploads to 0.

    -- Hugh

Re: size of file upload
by Fletch (Bishop) on Feb 13, 2006 at 00:21 UTC

    CGI returns a filehandle for the uploaded file which you should be able to pass to stat to see how big it is.

      Returning the form field as a variable, would $size = stat($file); work? Or would I need to use a filehandle?
Re: size of file upload
by zentara (Cardinal) on Feb 13, 2006 at 12:58 UTC
    I saw this posted a few days ago, I havn't tested it.
    #!/usr/bin/perl use warnings; use strict; use CGI::UploadEasy; my $uploaddir = '/path/to/upload/directory'; my $ue = CGI::UploadEasy->new(-uploaddir => $uploaddir); my $info = $ue->fileinfo; my $cgi = $ue->cgiobject; print $cgi->header; print $cgi->param('myParam'), "<br />\n"; for my $file ( keys %$info ) { print "Read $info->{$file}{bytes} bytes of $file<br />\n"; }

    I'm not really a human, but I play one on earth. flash japh