Reputation: 1264
Is it possible to force file download to user's browser (with the standard dialog prompt of course)? To be triggered by the server. Basically I'm thinking of pushing a file to the browser coming from server filesystem. Or is this not possible because of security sandbox? If this is not possible, is there a different way very close to this? I do not want to send the file w/o the user's consent. I can think of two step approach, first to prompt user of incoming data, and let user click on an OK button which triggers download, but near the end of download, user will get another confirmation box (the standard download prompt which asks to open or save). It would be nice if its possible with one step.
Upvotes: 3
Views: 2350
Reputation: 28722
Use an ajax json script that polls the server every 5 seconds or 10 seconds, when the server has a file ready responds with a positive answer "I have a file" have an iframe move to that url where the file is, and then it's handled as a normal download.
I have provided a little example of how I should think that it should work, so you have something to work from. I haven't checked it for bugs though, it's more a proof of concept thing.
jQuery example(without json):
$.ajax('/myserverscript.php?fileready=needtoknow').done(function(data)
{
if(data.indexOf("I have a file") != -1)
{
xdata = data.split('\n');
data = xdata[1];
document.getElementById('myiframe').location.href = data;
}
});
PHP code
$x = filecheckingfunction();// returns false if none, returns url if there is a file
if($x !== false)
{
echo 'I have a file\n';
echo $x;
}
Upvotes: 3
Reputation: 8767
Since you are aware that you must prompt the user, try using a plain hyperlink with type="application/octet-stream"
.
You can also use: "content-disposition: attachment"
in the header.
Upvotes: 0
Reputation: 15379
It's definitely possible. Assuming you want this to be triggered by the server, you would simply send them this header:
Location: http://www.foo.com/path/to/file
Where foo.com
is your domain and it contains the path to the file. This would send the user over to your file link and have them auto-download as a result.
Now, to get around the issue where your browser views the content, you would need server-side code to issue Content
header information like so (using PHP as an example):
<?php
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($file));
header('Content-Disposition: attachment; filename=' . $file);
readfile($file);
?>
Hopefully this works well enough as pseudo-code to get you started. Good luck!
Upvotes: 3