#!/usr/local/bin/perl -w use strict; use CGI; use IO::File; use POSIX qw (tmpnam); my $finalname = '/tmp/uploaded.file'; { my $tmpnam; my $html = new CGI; print $html->header; if (!defined ($html->param ('uploadname')) || $html->param ('uploadname') eq '') { print while (); print $html->end_html; exit; } my $fn = $html->param ('uploadname'); my $fh = $html->upload ('uploadname'); my $fd = ''; if (!defined ($fh)) { print "\$fh is not defined!\n"; print $html->end_html; exit; } while ((length ($fd) <= (64 * 1024)) && read ($fh, my $buffer, 1024)) { $fd .= $buffer; } if (length ($fd) == (64 * 1024)) { print "File too big!"; print $html->end_html; exit; } # # Get a temporary file name we know is ours. The loop resolves the race condition possibility. # for (;;) { $tmpnam = tmpnam (); sysopen (TMP, $tmpnam, O_RDWR | O_CREAT | O_EXCL) && last; } close (TMP); # # Create the temporary input file for the size-getter and thumbnail maker # if (open (SOURCE, ">$tmpnam")) { print SOURCE $fd; close SOURCE; } else { print "Couldn't open $tmpnam for writing: $!"; print $html->end_html; exit; } rename ($tmpnam, $finalname); print "File uploaded OK, saved as $finalname"; exit; } __DATA__ File Upload Test

Select file to upload:

 
#### #!/usr/local/bin/perl -w use strict; use Carp; use LWP::UserAgent; use LWP::Simple; use HTML::Form; my $site = 'http://linux/release/cgi-bin/htmlformtest.pl'; my $testfile = './testfile.txt'; # # # { if (!-e $testfile) { open (FH, ">$testfile") || die $!; print FH "\nThis is a test file.\n"; print FH "It has been uploaded via HTML::Form\n"; print FH "And it has 5 lines in it.\n\n"; close FH; } my $req = get ($site); die "Eeek! Request failed.\n" if !$req; # # # my $form = HTML::Form->parse ($req, $site); if ($form->find_input ('uploadname')) { $form->value ('uploadname', [$testfile => [$testfile]]); my $userAgent = LWP::UserAgent->new; my $res = $userAgent->request ($form->click); die sprintf ("Eeek! Request failed (%s)\n", $res->status_line) unless ($res->is_success); print "\n", $res->content, "\n"; print "I seem to have uploaded the file OK!\n\n"; } else { die "Eeek! Whatever page we got, didn't have 'uploadname' as a field!\n"; } }