简体   繁体   中英

Detect start of download start / file transfer from client side only

I noticed that there is a question before asking how to " Detect when browser receives file download ".

This requires the server to send a cookie in order to complete the steps. However, I want to detect if the browser receives file only on client side, as I cannot modify anything on the server side.

The problem I am encountering is that I have to download many zip files from a website. The zip files are dynamically generated so there is no URL to download until I submit the request. First, I write a for loop to do that as follows.

function myfunc(i){
    setTimeout(function(){
    $("form").submit();
    },2000*(i)
}
for (i=1; i<4; i++) {
myfunc(i);
} //i

But there is a chance that before the browser receives the first file (i=1) , the browser will have already submitted the form requesting the second file (i=2) and cancel the request of first file. So I have to ensure the first file has started before requesting the second file.

ajax seems not to be an option as it seems to be unable to handle zip file download.

How can I do that?

Edit: You can also ise an ajax call to get a base64 string of the zip and then clientside convert it to a blob in html5. But that requires to base64 encode the file server side and it increases the file size by around 33%.


I would make an ajax call that checks is the file is already generated after starting the download with a timer:

$.ajax({
    type: 'HEAD',
    url: 'generatedfileurl',
    success: function() {
        alert('File found.');
    },
    error: function() {
        alert('File not found.');
    }
});

Then when the file is found I'd wait a few seconds and then start download nr2 since I assume that file nr1 is already downloading since it has already been generated.

It's far from ideal, I'd definitely recommend using cookies or something else serverside.

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