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

My code:
print "Content-Type: application/pdf\n"; print "Content-Disposition: attachment; filename=$MyPDF\n\n";
When the download finished and I try to open the file the file is corrupt and got 0 bytes. On my webserver this file got an correct filesize, and if I download via FTP I can open the file without a problem. Using application/x-pdf instead of the above does not help too. I tried with Content-Transfer-Encoding: binary still same result.


Edit: Okay, I failed this time again ;-)
When writing an reply for @Corion I just saw what I did wrong. When writing this, read @McA 's reply. Thanks guys, I really appreciate your help.

print "Content-Type: application/pdf\n"; print "Content-Disposition: attachment; filename=$MyPDF\n\n"; open FILE, "<", $MyPDF; my @aPDF = <FILE>; close FILE; print @aPDF;

Replies are listed 'Best First'.
Re: CGI pdf got 0 bytes after downloading - compression problem?
by McA (Priest) on Nov 20, 2014 at 14:08 UTC

    Hi,

    allow me to add some comments:

    • The line ending of a HTTP header line is CR LF. Most servers and clients are not rigid, but correct is:"...\r\n";
    • PDF-Files are binary files. So it's better to force binary read mode with:
      open FILE, "<", $MyPDF; binmode FILE;
    • You read the PDF file line by line into an array. That does not have any advantage in your case because you read in the whole file before printing it out. Therefor you could also do the following:
      binmode STDOUT; # read the whole file my $file = do { local $/ = undef; <FILE> }; my $length = length $file # additional header print "Content-Length: $length\r\n"; print "\r\n"; # http header end print $file;

      Sending the content-length to the client has the advantage that the client can give you a forecast about the remaining time of download. Test it with a BIG pdf file. You'll see the difference.

    Regards
    McA

Re: CGI pdf got 0 bytes after downloading - compression problem?
by McA (Priest) on Nov 20, 2014 at 13:17 UTC

    Hi,

    the interesting part is: How do you send the content of the PDF-File? When these two lines is everything you send to the client than it's obvious why your download has 0 Bytes. The HTTP body is missing.

    McA

Re: CGI pdf got 0 bytes after downloading - compression problem?
by Corion (Patriarch) on Nov 20, 2014 at 13:13 UTC

    Where do you send the file?