Auto start file download after form submission

2019-01-23 05:53发布

问题:

I have a web form that users complete online. When they press submit it will start a file download for them.

At the moment, I process the form submission and generate a suitable file for the user and fire it off with suitable headers. eg...

header('Content-type: "application/octet-stream"');
header('Content-Disposition: attachment; filename="yourfile.txt"');
header("Content-Transfer-Encoding: binary");

However, since this starts a download right away, the original form is left on screen by the browser.

I would really like to go to some "Thank you" screen once the download completes (or before the download starts). I know it is possible, because almost every download site you visit does this (normally to pump you full of adverts before the download starts).

So, How do I show a "Thank You" screen that starts the download after a second?

How would any solution proposed effect the behaviour of the back button, as I don't want the file downloading again without the form being refilled?

I am using PHP on the server and can rely on Javascript (and jQuery) being available on the client.

Thank you.

回答1:

You could send the form to the Thank you document and put there a META refresh to the file download:

<meta http-equiv="refresh" content="3;url=download.php">
<p>Thank you! The download will start in 3 seconds. If not, use this link to download the <a href="download.php">file</a></p>


回答2:

Add a second page that says something "thank you, your donwnload will start in a few seconds" and triggers the download using javascript:

$(document).ready(function(){
  window.setTimeout(function(){
    window.location = 'http://yourdownloadhost.com/file.zip';
  }, 1500);
});

or use a meta redirect.



回答3:

You can insert a hidden iframe into your page and submit your form to this iframe.