Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File upload with CGI_Lite.pm or cgi-lib.pl

Uploading Files

File upload with CGI_Lite.pm or cgi-lib.pl

by  tanderso  Posted    (Edited  )
<FORM METHOD="POST" ACTION="script.pl" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" SIZE="30" NAME="UPLOAD" ACCEPT="text/plain,image/gif">
</FORM>

You have to use the multipart/form-data enctype on the form.

I'm not sure if that ACCEPT thing works since I haven't had too much luck with it myself, but I saw it in the docs. It's supposed to prevent the uploading of unwanted types.

Anyway, this is the back-end Perl code to receive the file:

# CGI routines (I prefer CGI_Lite over CGI)
use CGI_Lite;
my $cgi = new CGI_Lite;
my %in = $cgi->parse_form_data;

# get the file from the input array
my $upload = $in{"UPLOAD"};

# path
my $path = "/path/to/your/file";

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

# check if it's there, and write it to disk
if ($upload)
{
# if it's a gif
if ($upload=~/GIF/)
{
open (IMAGE, ">$path/filename.gif") || CgiDie("Cannot open $path/filename.gif for writing: $!");
binmode(IMAGE);
unless (flock (IMAGE, LOCK_EX)) {CgiDie("Cannot lock $path/filename.gif: $!");}
print IMAGE $upload;
close(IMAGE);
}

# if it's plain text
else
{
open (TEXT, ">$path/filename.txt") || CgiDie("Cannot open $path/filename.txt for writing: $!");
unless (flock (TEXT, LOCK_EX)) {CgiDie("Cannot lock $path/filename.txt: $!");}
print TEXT $upload;
close(TEXT);
}
}
else {CgiDie("Error: file did not upload.");}

This, of course, assumes that you are only accepting gifs or plain text. You can actually upload any filetype you want. You have to figure out how to determine it's type though. For instance, gifs have "GIF" in their header. You also have to figure out how to name the file, either by a common system or let the user determine a name (potentially dangerous). You don't have to save the file either... you could print it to the screen. It's just a string containing the file contents, so you could print plain text directly, or you could put an image into the src of an image tag. Or you could perform computations and alterations to it before printing or saving it.

BTW, make sure your destination directory is writable (ie. CHMOD 777) or you won't be able to write the file. It is generally a good idea for security reasons to keep your data directory outside of your web directory tree.

And here's that CgiDie subroutine I included in the code:

sub CgiDie
{
my ($message) = @_;
print $message;
die $message;
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top