Looks like you need to read the documentation on file upload basics again. The sample code they have is:
use autodie;
# undef may be returned if it's not a valid file handle
if ( my $io_handle = $q->upload('field_name') ) {
open ( my $out_file,'>>','/usr/local/web/users/feedback' );
while ( my $bytesread = $io_handle->read($buffer,1024) ) {
print $out_file $buffer;
}
}
There are some stylistic differences to your code, but the important thing to note that is that when your code runs this line:
$file=$cgi->upload('text');
Then $file
contains an open filehandle. It does not contain the filename. This means that there are at least three errors in these lines of your code:
$directory="var/www/cgi-bin/uploads";
open UPLOAD, ">$directory$file";
- The value you store in
$directory
should almost certainly start with a /
(so it's /var/www/cgi-bin/uploads
).
- You also need another
/
between $directory
and $file
(otherwise, it will contain something like /var/www/cgi-bin/uploadsmyfile.dat
).
- You need to call
$cgi->param('text')
to get the name of the file that is being uploaded.
This is what is stopping your program from working. The upload section of your code should look like this:
my $filename = $cgi->param('text');
my $fh = $cgi->upload('text');
my $directory = '/var/www/cgi-bin/uploads';
open my $upload_fh, '>', "$directory/$filename"
or die "Can't open '$directory/$filename': $!";
print $upload_fh $_ while <$fh>;
Note that I've made some stylistic improvements here:
- Used 3-argument version of
open()
- Used lexical filehandles
- Checked the success of the
open()
call and killed the program with a useful error message if it fails
All in all, you seem to have learned CGI programming from a resource that is about twenty years out of date. Your code looks like it comes from the 1990s.
A few other tips:
- Always
use strict
and use warnings
.
- Indirect object notation (
new CGI
) is potentially very confusing. Use CGI->new
instead.
- We've known that the HTML-generation functions in CGI.pm are a terrible idea since the end of the last millennium. Please don't use them. Many good templating solutions are available for Perl.
- Writing a CGI program in 2017 is a terrible idea. Take a look at CGI::Alternatives for an introduction to Modern Perl Web Development tools.