This subroutine finally resulted in a correct download.
sub send_file {
my ($cgi, $dir, $file) = @_;
my $path = "$dir$file";
$cgi->charset('');
#$|=1; ### THIS FOULS UP THE DOWNLOAD "SAVE AS..." DIALOGUE
$|=0; #SO LET'S BE EXPLICIT ABOUT SETTING THIS CORRECTLY!
my $fn;
open ($fn, "< :raw", $path) or die "Sorry, unable to open the file: $t
+empfile. $!\n";
binmode($fn);
my @document = <$fn>;
close $fn;
my $len;
$len += length $_ for @document;
print"Content-type:application/x-download\n";
print"Content-disposition:attachment; filename=$file\n";
print"Content-length:$len\n\n";
binmode STDOUT;
print @document;
return;
} #END SUB send_file
In place of the print @document; line above, either of the following two options worked equally well, but with more lines.
my $in_fh;
open($in_fh, "<", $path)
|| die "$0: cannot open $path for reading: $!";
binmode($in_fh) || die "binmode failed";
print while <$in_fh>;
close($in_fh) || die "couldn't close $path: $!";
OR...
my $BUFSIZ = 64 * (2 ** 10);
my ($in_fh, $buffer);
open($in_fh, "<", $path)
|| die "$0: cannot open $path for reading: $!";
binmode($in_fh) || die "binmode failed";
while (read($in_fh, $buffer, $BUFSIZ)) {
unless (print $buffer) {
die "couldn't write to STDOUT: $!";
}
}
close($in_fh) || die "couldn't close $path: $!";
There were likely multiple puzzle pieces which all had to be correct at the same time for this to work, and I was unlucky enough to have just one problem or another in my code at any given time to spoil it. One of the major ones was setting the STDOUT to 'binmode'. This prevented the garbled text. Another major one was not having the correct placement, and number, of newlines after the headers. And, for me at least, one of the big ones was the discovery that setting the print handle to "hot", i.e. $| = 1 would prevent the client from opening the download dialogue, with log errors claiming the headers had not been sent, even though I had explicitly printed them and had bypassed the CGI module for this.
I do not know what the purpose of buffering the download is in the final example, but I think this form would be useful where file sizes made slurping them fully into memory inconvenient. In any case, I found more than one way to do it.
As this is not the first time I have needed to do something like this, and as my earlier code of a similar nature seems to have been difficult to adapt to the needs of this new circumstance, I hope to remember this solution and find it more generally applicable. Thank you to those who gave helpful suggestions.
|