gilbert has asked for the wisdom of the Perl Monks concerning the following question:

In my program I am trying to have a user upload a file
to an apache web server. but my current code does not
upload anything. Help please.

use strict; use CGI qw(:standard); print header(),start_html('Upload Files'); print start_multipart_form(); print h2('Upload Files'); print "Select the File: ", filefield(-name=>'filepath', -size=>30, -maxlength=>100), p, reset, submit('submit', 'Upload File'); print end_form(); if (my $filehandle = param('filepath')) { doUpload(); } else { print "Choose a file to upload"; } sub doUpload { my ($bytes, $buffer, $bytesread); my $filehandle = CGI::param('filepath'); open OUTFILE, '>$filehandle' or die "Couldn't open output file: $!\n"; while ($bytes = read($filehandle, $buffer, 1024)){ $bytesread += $bytes; print OUTFILE $buffer; } warn "Recieved $bytesread bytes"; close OUTFILE; } print end_html;

Replies are listed 'Best First'.
Re: need help with file uploading
by stephen (Priest) on Jun 19, 2001 at 22:39 UTC
    In this code:
    sub doUpload { my ($bytes, $buffer, $bytesread); my $filehandle = CGI::param('filepath'); open OUTFILE, '>$filehandle' or die "Couldn't open output file: $!\n";
    You're using single quotes when opening OUTFILE. Therefore, you're always writing to a file named '$filehandle'-- not the contents of the variable, but the string '$filehandle' itself. Change those to double quotes. Better yet, use File::Temp to create a temporary file if you're using 5.6.

    Additionally, you should use upload() instead of param() to get the uploaded filehandle for security reasons. Namely, instead of saying:

    my $filehandle = CGI::param('filepath');
    say
    my $filehandle = upload('filepath') or die "No file uploaded!";
    Since upload() returns undef if there's no upload field with the given name, it'll error out if the user didn't upload a file. More secure, since the user can't try to mess you up by providing a text input to 'filepath'.

    Note: Code untested, since I don't have a web server handy.

    stephen