Photo Upload Form Fields

I have added an optional photo upload field to the online admission application I am developing. This clever feature is ubiquitous in online communities and photo sharing sites, but how does it work. If you use the CGI library in PERL, it is quite easy.

First, create a multipart form instead of a standard form:

$output_text .= start_multipart_form;

Include a file upload field in your form:

$output_text .= filefield(-name=>’photo’, -default=>”, -size=>30, -maxlength=>80 -class=>’BodyNormal’);

When processing the form, capture the file handle using upload() instead of param(). This ensures a legit filehandle.

$fh = upload(‘photo’);

Then write the contents of the file to the desired location:

$outfile = $basedir . ‘/’ . $uploaddir . ‘/’ . param(‘student_id’) . ‘.jpg’;
open (OUTFILE, “>$outfile”);
binmode(OUTFILE);
flock(OUTFILE,2);
while ($bytes=read($fh,$buffer,1024)) {
print OUTFILE $buffer;
$totalbytes += $bytes;
}
close OUTFILE;

Note that I have not yet added a trap for excessively large files. Mostly, this is a favor to the user, who will have to wait a long time for the form to process if the upload image is too large. You can add the trap by keeping track of the number of bytes uploaded and exiting the write loop/deleting the file if the total exceeds a certain amount.

I have also restricted the file type to JPG in order to ensure higher image quality and prevent people from trying to run executables off my server. It would be good practice to add an error message if someone tries to upload an image of a different type.

Comments are closed.