in reply to Re: Re: Re: CGI Uploading (repost)
in thread CGI Uploading (repost)

That's what I thought it was, can you tell me what's wrong with my code below then? I get an error on my open (OUTFILE.. and I receive a software error.
#!/usr/bin/perl -w use warnings; use CGI qw/:standard/; use CGI::Carp 'fatalsToBrowser'; use POSIX; print header, start_html('upload form'); print start_form(), table( Tr( td("File: "), td(filefield(-name=>'upload', -size=>50, -maxlength=>80), ), ), Tr( td(), td(submit('button','submit'), ) ) ), end_form(), hr; if (param()) { my $filename = param('upload'); while (<$filename>) { print; } open (OUTFILE,">>/home/myname/public_html/upload") || die $!; while ($bytesread=read($filename,$buffer,1024)) { print OUTFILE $buffer; print "the thing is open"; } close $filename; print "The file should be uploaded if everything went right, which it +probably didn't.\n"; }

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: CGI Uploading (repost)
by benn (Vicar) on Apr 17, 2003 at 09:21 UTC
    There are a few points here.
    • To upload a file, the HTML form needs to have a 'multipart/form-data' encoding type - this is done by 'start_form(-enctype=>'multipart/form-data'), instead of just start_form()'
    • while (<$filename>) {print;} will 'empty' the filehandle. As I explained here, CGI.pm gives you a *handle* to the file it uploaded-and-decoded-and-saved-as-a-tmpfile, allowing you to read from it and write the data to somewhere else (OUTFILE). (For that reason, I generally call it $filehandle). You've been confused by the CGI docs here - that bit of example code is actually *two* examples, as evidenced by the comments - one to read-and-print a text file, one to read-and-save a binary file. you want the second one - you can throw away that while<$filename> structure.
    • You open'ed OUTFILE, so you close OUTFILE, not $filename. $filename is something 'lent' to you by CGI.pm - don't worry - it'll take care of it itself :)
    Hope this clears some stuff up.
    Ben
Re: Re: Re: Re: Re: CGI Uploading (repost)
by marinersk (Priest) on Apr 17, 2003 at 15:35 UTC
    Another point is that you are reading the file in binary mode but you are not using binmode() to ensure the file you are writing is binary. When it doesn't matter, it doesn't matter, but where it does matter, it can really matter.  :-)