outputting to browser after sending binary file

robgudgeon used Ask the Experts™

Using code from this site, I've managed to create a CGI that will send a binary file to a user. My question is: after the header has been sent, can I write to the browser anymore?

My code essentially looks like this:

elsif ($q->param('download')) {

     my $file = "../htdocs/HKBeta.exe";
     my @stats = stat($file);
     $|++; # Disable output buffering
     my $nl=$/; # Save the newline character
     undef $/;
     open(F,$file) || die $!;
     binmode(F); # Open the file in binary mode
     my $file_contents=<F>; # Read the entire file into a single variable

     $/=$nl; # Restore the newline character

     print header(     -type => 'application/octet-stream',
                                        -Content_Disposition => 'attachment; filename=HKBeta.exe',
                                        -Content_Length => $stats[7],

     print $file_contents;

        print "<p>** hello. testing.....";

Clicking the download button causes the save-as window to popup but I can't do anything after this - should this be possible?

thanks a lot
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try this before display_footer()
print "Content-type: text/html\n\n";


Basically the answer is no. The browser expects a single resource for each request. The file that you are downloading represents one resource and the HTML would represent a second.

ow having said that a thought has just occured to me which I have never seen anyone try, and I have a hunch it won't work, but if you are prepared to put in the effort you might just get lucky.

It is possible to send a multipart mime type. Typically this is used in emails when someone attaches a binary file, such as an image, to an email.

My thought is what would happen if this was sent to a browser.

To form a multipart message send your self an email with a mall binary attachment in it and take a look at the message source.

The important thing to note is that each part of the message has a boundary which is marked with a series of characters. The characters used are recorded in the header of the message part.

In your case the messages part would be the current stuff you are downloaded and the HTML as a second part. As I say I've never tried it and don't know anyone who has but it could be an interesting experiment.

Other than that there is no way to do it.

i once tried combining header requests such as:


together with


which is nearly impossible...


Thanks - I'll give it a go!
goodluck! ;)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial