php 表单提交后自动启动文件下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1509116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto start file download after form submission
提问by Rik Heywood
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.
我在服务器上使用 PHP,可以依赖客户端上可用的 Javascript(和 jQuery)。
Thank you.
谢谢你。
回答by Gumbo
You could send the form to the Thank youdocument and put there a META refreshto the file download:
您可以将表单发送到感谢文档,并将META 刷新放在文件下载中:
<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>
回答by middus
Add a second page that says something "thank you, your donwnload will start in a few seconds" and triggers the download using javascript:
添加第二个页面,上面写着“谢谢,您的下载将在几秒钟内开始”并使用 javascript 触发下载:
$(document).ready(function(){
window.setTimeout(function(){
window.location = 'http://yourdownloadhost.com/file.zip';
}, 1500);
});
or use a meta redirect.
或使用元重定向。
回答by middus
You can insert a hidden iframe into your page and submit your form to this iframe.
您可以将隐藏的 iframe 插入您的页面并将您的表单提交到此 iframe。

