Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file and redirect...or alternative

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.

I can't initiate download on page2.html because most browsers will flag security warnings if a download link isn't directly clicked on.

How is something like this accomplished using javascript or jquery? Obviously the following doesn't work but it's meant for illustrative purposes:

document.getElementById("foo").onclick = function(){
     window.location = "/download.exe";
     window.location = "/page2.html";
}
like image 994
Kyle Cureau Avatar asked Dec 07 '10 04:12

Kyle Cureau


Video Answer


2 Answers

You could use a link to the file and onclick to trigger "go to the next page shortly".

<script>
function thanks() {
    setTimeout(function () {
        document.location.pathname = "page2.html";
    }, 1000);
}
</script>

<a href="file.exe" onclick="thanks()">Download now!</a>
like image 109
Chris Morgan Avatar answered Oct 15 '22 19:10

Chris Morgan


You can initiate the download on page 2 by having page2.html "change" its location (to your download URL) once the page is loaded:

$(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.

like image 42
Matt Ball Avatar answered Oct 15 '22 20:10

Matt Ball