Practical Exercise: File upload

CGI can also be used to allow users to upload files. Your trainer will demonstrate and discuss this. Source code for this example is available in your cgi-bin directory as upload.cgi

First off, you need to specify an encoding type in your form element. The attribute to set is ENCTYPE="multipart/form-data".

<html>
<head>
<title>Upload a file</title>
</head>
<body>
<h1>Upload a file</h1>

Please choose a file to upload:

<form action="upload.cgi" method="POST" enctype="multipart/form-data">
<input type="file" name="filename">
<input type="submit" value="OK">
</form>
</body>
</html>

CGI handles file uploads quite easily. Just use param() as usual. The value returned is special -- in a scalar context, it gives you the filename of the file uploaded, but you can also use it in a filehandle.

#!/usr/bin/perl -w

use strict;
use CGI 'param';

my $filename = param('filename');
my $outfile = "outputfile";

print "Content-type: text/html\n\n";

# There will probably be permission problems with this open 
# statement unless you're running under cgiwrap, or your script
# is setuid, or $outfile is world writable.  But let's not worry
# about that for now.

open (OUTFILE, ">$outfile") || die "Can't open output file: $!";

# This bit is taken straight from the CGI.pm documentation --
# you could also just use "while (<$filename>)" if you wanted

my ($buffer, $bytesread);
while ($bytesread=read($filename,$buffer,1024)) {
        print OUTFILE $buffer;
}

close OUTFILE || die "Can't close OUTFILE: $!";

print "<p>Uploaded file and saved as $outfile</p>\n";

print "</body></html>";