简体   繁体   中英

HTML form to go to new page and start download

I have an HTML form like so:

<form method="post" enctype="multipart/form-data" action="script.php" align="center">
    <input type="submit" value="Run Program"/>
</form>

Then I have the PHP page, script.php. I would it to be displayed and also begin a download automatically. However, when I add the header for starting the download:

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $_FILES['upload']['name'] . '.tbx');
header('Content-Type: application/force-download');
header('Content-Length: ' . filesize($tbx));

the download is started but the page itself is not loaded (probably because the headers say that we are just going to transfer a file). How do I make the page properly display and automatically start a download?

You can't do that server-side. You have to do that client-side.

You can only send one resource at a time over HTTP! Just send a page that includes a JavaScript redirect to your download script.

You need to load the HTML page first, then at the end of the page perform a JavaScript location request to the download file.

<html>
... your HTML ....
<script type="text/javascript">
document.location = '... location of file to download ...';
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM