我如何知道何时从URL下载完成?

Ser*_*sen 6 javascript

在我的项目中,我使用类似以下函数的内容来重定向用户以下载文件

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

众所周知,当我调用此函数时,浏览器只会提示下载对话框,并且不会中断我的应用程序流.我想要做的是确定下载完成或取消的时间.

应该有类似onLoad,onFinishedLoading,onConnectionEnd和等,但我无法找到任何东西.

Wat*_*oll 5

如果以这种方式下载文件,则无法确定下载进度。

如果您使用 下载文件XMLHttpRequest,那么您可以监听加载、错误和进度事件,如下所示:

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');
  });
});
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <button id="download">Download</button>
    <script src="script.js"></script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)