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

It's one of those crazy situations were I'm using a chunk of code in dozens of places and all have worked fine, including on this very site that is causing the error:

Cannot read sourcefile: Bad file descriptor at...

This question has been asked before, but the solution doesn't apply here (my html is fine).

It opens the file (I see it in the directory) but it has 0 bytes. Permissions for the folders are 0755 and I've tried eliminating the path thinking that was it. I've tried everything I can think of and to no avail. Ideas? TIA!

HTML: <form action="some.cgi" method="post" enctype="multipart/form-da +ta"> PERL: my $image = $query->param('image'); my $lgimage = &upload_file($image,"../acme/images/products"); . . . sub upload_file { $| = 1; #flush the output buffer my ($sourcefile,$path) = @_; my ($buffer, $bytes); $sourcefile =~ /([\w .-]+)$/i; #strip off path stuff my $newfile = $1; $newfile =~ s/ //; open (OUTFILE, ">$path/$newfile") or die "Cannot open $newfile: $!" +; binmode(OUTFILE) or die "Cannot binmode: $!"; while (read($sourcefile, $buffer, 1024) or die "Cannot read sourcef +ile: $!") { print OUTFILE $buffer or die "Cannot print to buffer: $!"; } close(OUTFILE) or die "Close: $!"; chmod (0664, ">$path/$newfile") or die "Cannot chmod: $!"; return ($newfile); }


—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re: Bad file descriptor when uploading file via CGI
by Errto (Vicar) on Apr 07, 2005 at 04:06 UTC
    My first suggestion is to use the newer upload method in CGI.pm so you don't have to deal with the magic-ness of the filehandle/string duality. It may not help but it removes a potential source of problems. The other issue is that this code
    read($sourcefile, $buffer, 1024) or die "Cannot read sourcefile: $!"
    looks a little funny to me, because read can return zero (a false value) when it reaches the end of the file but still not hit an error condition. That's all I can think of for now.

      Thanks for the upload() tip. I found an example here at the monastery and plugged it into my code. Worked wonderfully.

      Here's my revised code:

      $| = 1; my ($file,$path) = @_; my $filename = $query->upload($file); my $buffer; open(OUTPUT, ">$path/$filename"); binmode($filename); binmode(OUTPUT); while( read($filename, $buffer, 64*2**10) ) { print OUTPUT $buffer; } close(OUTPUT); return ($filename);

      I would still like to know what the original problem was, but right now I just need a solution.


      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot