Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

On my project I use something like the following function to redirect users in order to download a file

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

As we all know, when I call this function, browser only prompts a download dialog and does not interrupt my application flow. What I would like to do is to determine when this download completed or cancelled.

There should be something like onLoad, onFinishedLoading, onConnectionEnd or etc but I couldn't find anything.

like image 590
Serkan Yersen Avatar asked Jun 14 '11 15:06

Serkan Yersen


People also ask

When I download a file where does it go?

You can find downloads on Android in My Files or File Manager. You can find these apps in the app drawer of your Android device. Within My Files or File Manager, navigate to the Downloads folder to find everything you downloaded.


1 Answers

You can't determine download progress if you download the file that way.

If you download the file using XMLHttpRequest, then you can listen for load, error and progress events like this:

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>
like image 92
Rodrigo5244 Avatar answered Sep 20 '22 22:09

Rodrigo5244