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

In the following snippet of code:

use CGI; sub write_file { $filename = $query->param('portrait'); open (OUTFILE, "> directory/file.xxx"); while ($bytesread = read ($filename, $buffer, 1024)) { print OUTFILE $buffer; } close $filename; close OUTFILE; }
...the $filename variable is getting set to the value of a <input type="file" name="portrait" field> from a "ENCTYPE=multipart/form-data" form which allowed the user to browse their computer and select a file for upload. No big deal.

What I don't understand is how that $filename variable suddenly becomes a filehandle argument for the read function. Doesn't the $filename contain only the path the user selected on their computer? How the hell does the server upload the file given only this information? There has to be a lot more happening with "ENCTYPE=multipart/form-data" forms that's invisible to me. What is it?

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar";
$nysus = $PM . $MCF;

Replies are listed 'Best First'.
Re: How does file uploading work in multipart form?
by Corion (Patriarch) on May 20, 2001 at 14:59 UTC

    The CGI.pm documentation tells us that the filename returned doubles as a file handle, so you can directly read from that parameter. This is some magic that best works when not looked closely at :). The documentation then goes on recommending the upload() function, available since version 2.47 :

    $fh = $query->upload('uploaded_file'); while (<$fh>) { print; }

    Using upload() gives you the additional advantage of returning an array of filehandles if there are many upload fields with the same name.