This tutorial is about how to upload files from a HTML form with CGI::Application.
First read the CGI::Application tutorial if you don't know how the module works.
If you plan to create a form not from a HTML template but from a query object, check out the section CREATING A FILE UPLOAD FIELD
in the documentation for CGI.pm:
# perldoc CGI
NOTE: A HTML form containing a file field must be encoded as a multipart form:
open (OUTFILE, ">>/usr/local/apache/htdocs/news.html");
while ($bytesread = read($filename, $buffer, 1024)) {
print OUTFILE $buffer;
}
Be careful when permitting uploads to the server.
You have to consider to untaint the filename if you are running in taint mode (which you should).
See Perl taint mode for details.
You should also set a file size limit, and always use binmode together with the open statement to permit users uploading any type of file (both text and binary files, which are treated in different ways on MS Windows), as shown in the example below:
# Retreive the uploaded file
my$bytes_retreived = 0;
my$bufsize = 1024;
my$limit = 1024 * 1024; # 1 MB limit
my$buffer = '';
# Open tempfile for writing
open (TMPFILE, ">$fullpathfilenametmp");
binmode TMPFILE; # To be sure MS Windows binary files don't get corrupted.
while (($bytes_retreived <= $limit) && read ($fh, $buffer, $bufsize))
{
print TMPFILE $buffer;
$bytes_retreived += $bufsize;
}
close TMPFILE;
# Failure (file too big), remove tempfile
if ($bytes_retreived >= $limit)
{
$error .= "Error: File <b>$filename</b> too big. (max size = " . filesizesuffix($limit) . ")<br>";
unlink $fullpathfilenametmp
or $error .= "Error: Deleting uploaded part of too big file failed: $!<br>";
}
# Success, rename tempfile to uploaded file
else
{
rename $fullpathfilenametmp, $fullpathfilename
or $error .= "Rename file failed: $!<br>";
$msg .= "File <b>$filename</b> uploaded succesfully.<br>"unless $error;
}
}
Check the following files for a working demo for printing an uploaded file's contents to the browser: