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

Hello Monks, I have a perl cgi script which outputs html (Content-type:text/html). Also I have another perl script which downloads a file (Content-Type:application/x-download). I need some giudance here . I need to get the html o/p and download file through just a single CGI url . Stuff I tried : 1. ) Adding 2 content-types in a single file. Only the HTML got the printed and the download got garbled. 2.) inserting the download script in the html script through print redirect . Inserting the script before content-type:text/html just got the download . Inserting the download script after the content-type:text/html got the cgi url for download printed. Anyhelp is appreciated.
  • Comment on Perl CGI : Output to HTML and download a file

Replies are listed 'Best First'.
Re: Perl CGI : Output to HTML and download a file
by Corion (Patriarch) on Aug 12, 2014 at 11:22 UTC

    You cannot do download and display in the same request.

    I suggest that you add a CGI parameter, type and use it as follows:

    my $type= $q->param('type'); $type ||= 'display'; if( 'display' eq $type ) { # output Content-Type: text/html # Output HTML page } elsif( 'download' eq $type ) { # output Content-Type: application/x-download # Output file } else { # Should never get here unless somebody has misconfigured the scri +pt or is playing around with the parameters # output Content-Type: text/html # Output HTML page };

    If you want to do "both", display and download, you need to first display the HTML page and then redirect to the download link.

      Thank you Corion. I tried the type parameter and it seems to work well to display the html content. however the print CGI->redirect after the display part of code doesnt work properly . "Status: 302 Found Location:<exceldownloadfile-script>" is getting printed.

        I think now is a good moment to familiarize yourself with the different types of redirect, and how HTTP and HTML interact in general.

        I recommend looking at the usual ways that the download sites do this. The two most common ways are a <meta http-equiv="refresh; URL=..."> or using Javascript to fetch the download URL.