How do I know when a download from a URL is complete?

In my project, I use something like the following function to redirect users to upload a file

function promptDownload(file){ location.href = "http://example.com/downloads/"+file; } 

As we all know, when I call this function, the browser requests a download dialog and does not interrupt the application flow. What I would like to do is determine when this download will be completed or canceled.

It should be something like onFinishedLoading , onFinishedLoading , onConnectionEnd or etc, but I could not find anything.

+6
source share
1 answer

You cannot determine the download speed if you download the file this way.

If you upload a file using XMLHttpRequest , you can listen to download events, errors and progress, for example:

 function log(message) { return function () { alert(message); }; } function download(file, callback) { var request = new XMLHttpRequest(); request.responseType = 'blob'; request.open('GET', file); request.addEventListener('load', log('load ' + file)); request.addEventListener('error', log('error ' + file)); request.addEventListener('progress', log('progress ' + file)); request.addEventListener('load', function () { callback(request.response); }); request.send(); } function save(object, mime, name) { var a = document.createElement('a'); var url = URL.createObjectURL(object); a.href = url; a.download = name; a.click(); } document.querySelector('#download').addEventListener('click', function () { download('test.pdf', function (file) { save(file, 'application/pdf', 'test.pdf'); }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <button id="download">Download</button> <script src="script.js"></script> </body> </html> 
+2
source

Source: https://habr.com/ru/post/890515/


All Articles