[英]How do I know when download from a URL is completed?
On my project I use something like the following function to redirect users in order to download a file在我的项目中,我使用以下 function 来重定向用户以下载文件
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.众所周知,当我调用这个function时,浏览器只会提示一个下载对话框,并不会中断我的应用流程。 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.应该有类似onLoad
、 onFinishedLoading
、 onConnectionEnd
等的东西,但我找不到任何东西。
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:如果您使用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');
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="download">Download</button>
<script src="script.js"></script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.