PROCESSING A FILE UPLOAD FIELD IN PERL

Basics

When the form is processed, you can retrieve an IO::Handle compatible handle for a file upload field like this:

$lightweight_fh = $q->upload(‘field_name’);
# undef may be returned if it’s not a valid file handle
if (defined $lightweight_fh) {
# Upgrade the handle to one compatible with IO::Handle:
my $io_handle = $lightweight_fh->handle;
open (OUTFILE,’>>’,’/usr/local/web/users/feedback’);
while ($bytesread = $io_handle->read($buffer,1024)) {
print OUTFILE $buffer;
}
}

In a list context, upload() will return an array of filehandles. This makes it possible to process forms that use the same name for multiple upload fields.

If you want the entered file name for the file, you can just call param():

$filename = $q->param(‘field_name’);

Different browsers will return slightly different things for the name. Some browsers return the filename only. Others return the full path to the file, using the path conventions of the user’s machine. Regardless, the name returned is always the name of the file on the user’s machine, and is unrelated to the name of the temporary file that CGI.pm creates during upload spooling (see below).

When a file is uploaded the browser usually sends along some information along with it in the format of headers. The information usually includes the MIME content type. To retrieve this information, call uploadInfo(). It returns a reference to a hash containing all the document headers.

$filename = $q->param(‘uploaded_file’);
$type = $q->uploadInfo($filename)->{‘Content-Type’};
unless ($type eq ‘text/html’) {
die “HTML FILES ONLY!”;
}

If you are using a machine that recognizes “text” and “binary” data modes, be sure to understand when and how to use them (see the Camel book). Otherwise you may find that binary files are corrupted during file uploads.