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

I want to download a file and redirect to another page. Downloading the file works, but how do I get a redirect? I heared about using javascript to get this done, but I wasn't successful yet. Can you please help me out?

My basic-script without redirect (working fine):

use strict; use warnings; use CGI; my $oCGI = new CGI; my $p_filename= $oCGI->param("filename"); print "Content-Type: application/x-download\n"; print "Content-Disposition: attachment; filename=$p_filename.pdf\n\n"; unlink $p_filename;

How do I add the Javascript part? The following doesnt work:

use strict; use warnings; use CGI; my $oCGI = new CGI; my $p_filename= $oCGI->param("filename"); print "Content-Type: application/x-download\n"; print "Content-Disposition: attachment; filename=$p_filename.pdf\n\n"; print ' <html> <head> <title>Redirect</title> <script type="text/javascript"> window.onload = function(){ window.location = "my_new_url.pl?param1=123"; } </script> </head> </html>'; unlink $p_filename;

Replies are listed 'Best First'.
Re: Perl CGI download file and redirect
by Corion (Patriarch) on Nov 17, 2014 at 14:15 UTC

    You need to reverse the order of your steps. Your current approach is

    1. Send the file to download (which is not HTML)
    2. Display the "thank you for downloading" page (which is HTML)

    Instead of doing it in that order, do it the other way around

    1. Display the "thank you for downloading" page (which is HTML)
    2. Issue a redirect or popup to the real download page
    3. Send the file to download (which is not HTML)

      Didn't I have to print headers first? If I print the header the file download is starting directly. How am I supposed to print first html then starting the download?

        Oh, sorry - I glossed over that part. You need a separate URL for sending the download. There you send the download headers. You have the URL for the "thank you" HTML page. There, you display the "thank you" message and then redirect (using META tags or Javascript) to the download page:

        <html> <head> <meta http-equiv="refresh" content="5; url=download.pl?filename=$p_fil +ename.pdf"> <body> <h1>Thank you!</h1> </body> </html>