javascript 下载文件并重定向...或替代方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4373440/
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
Download a file and redirect...or alternative
提问by Kyle
Users fill out a form. With a valid form, they click to download a file. I would like to be able to redirect them to another page (e.g., page2.html) AND initiate a download.
用户填写表格。使用有效的表单,他们单击以下载文件。我希望能够将它们重定向到另一个页面(例如,page2.html)并启动下载。
I can't initiate download on page2.htmlbecause most browsers will flag security warnings if a download link isn't directly clicked on.
我无法启动下载,page2.html因为如果未直接单击下载链接,大多数浏览器都会标记安全警告。
How is something like this accomplished using javascript or jquery? Obviously the following doesn't work but it's meant for illustrative purposes:
如何使用 javascript 或 jquery 完成这样的事情?显然,以下内容不起作用,但仅用于说明目的:
document.getElementById("foo").onclick = function(){
window.location = "/download.exe";
window.location = "/page2.html";
}
回答by Chris Morgan
You could use a link to the file and onclickto trigger "go to the next page shortly".
您可以使用指向该文件的链接并onclick触发“立即转到下一页”。
<script>
function thanks() {
setTimeout(function () {
document.location.pathname = "page2.html";
}, 1000);
}
</script>
<a href="file.exe" onclick="thanks()">Download now!</a>
回答by Matt Ball
You can initiate the download on page 2 by having page2.html"change" its location (to your download URL) once the page is loaded:
您可以通过page2.html在页面加载后“更改”其位置(到您的下载 URL)来启动第 2 页的下载:
$(function ()
{
setTimeout(function ()
{
window.location.pathname = '/download.exe';
}, 5000); // download the file in 5 seconds
});
I'm pretty sure (though not 100%) that won't trigger a security warning.
我很确定(虽然不是 100%)这不会触发安全警告。

