I'm using the following subroutine to send a binary (PDF) file back to the client's browser.

# IMPORTANT MODULES FOR THIS CODE... use CGI qw(-utf8); use File::Spec::Functions qw( catfile ); sub send_file { my ($cgi, $dir, $file) = @_; # $dir = '/var/www/download/'; # $file = 'MyLaTeXDocument.pdf'; my $path = catfile($dir, $file); open my $fh, '<:raw', $path or die "Cannot open '$path': $!\n"; $cgi->charset(''); #REMOVES PRIOR UTF-8 SETTING, AS THIS IS BINARY + FILE print $cgi->header( -type => 'application/octet-stream', -attachment => $file, ); binmode STDOUT, ':raw'; print while <$fh>; close $fh or die "Cannot close '$path': $!"; return; }

The browser console sees a string of characters returning in the response, but no download dialogue is opened.

Response headers

Connection Keep-Alive Content-Disposition attachment; filename="MyLaTeXDocument.pdf" Content-Type application/octet-stream Date Fri, 22 Sep 2023 11:13:27 GMT Keep-Alive timeout=5, max=100 Server Apache/2.4.52 (Ubuntu) Transfer-Encoding chunked

Response Payload

JVBERi0xLjUKJeTw7fg... [truncated...too lazy to type more]
Why won't the browser just open the "Save as..." dialogue? As it stands, the browser appears to do nothing, silently dropping this activity in background. What is lacking in this code?

Blessings,

~Polyglot~


In reply to Perl output is not inducing file download as expected by Polyglot

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.