问题
Is there any way to know that the browser event regarding file ready to download has fired? I have a script that generates a file, and while that is happening I show a laoding gif. Once this message appears: http://i.stack.imgur.com/CmZHE.png (file ready for download, script finished) I would like to stop the gif.
Is it possible to know this with JS? Using ajax is an option but would take longer since it would require multiple modifications on the system.
Thanks!
回答1:
I did it following this example: http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
For PHP, notice that this is how you send the cookie:
header('Content-type: application/octet-stream');
header('Set-Cookie: fileDownload=1; path=/');
header('Content-Disposition: attachment; filename='.$filename);
Path above is really important. Then JS also needs the path to remove the cookie, like this:
$.removeCookie('fileDownload', { path: '/' })
回答2:
I had the same issue and opted for a solution in two steps.
I think this is a good solution to show and hide a spinner.gif and/or waiting message while preparing file until the download is ready to begin.
- First I modifiy my anchor with jQuery to call my download function by ajax bby adding a
?cmd=prepareon my uri. This will prepare my PDF on server side and store it in a reachable folder by the client (for example domain.ext/documents/my_pdf_name.pdf).
HTML (bootstrap 3) :
<a href="/search/download" class="btn btn-primary pull-left download">
<i class="fa fa-file-pdf-o"></i> Download result in PDF
</a>
jQuery :
$(function() {
$('.download').on('click', function(e) {
e.preventDefault();
$('.loading').show();
url = $('.download').attr('href') + '?cmd=prepare';
$.ajax({
url: url,
type: 'get',
success: function(filename) {
console.log(data);
window.location = filename;
$('.loading').hide();
}
});
});
});
PHP server side :
// ajax call
if(addslashes($_GET["cmd"]) == "prepare") {
echo create_pdf($_SESSION["search"], $out="prepare");
die();
}
- When file is ready the function
create_pdf()will return filename to client and, on my success function in ajax query, I call awindow.location = filenamethat show me the "save as window".
The preparation of the document on server side is called by ajax, but the download is not !
- The problem resulting of this solution is storage of files you don't want to keep on server. So you can delete files older than x hours with a bash script. For example https://stackoverflow.com/a/249591/2282880
来源:https://stackoverflow.com/questions/18045200/javascript-jquery-file-download-ready-event