en.javascript.info/4-ajax/6-xhr-onprogress/progress.view/index.html
2015-02-27 13:21:58 +03:00

63 lines
1.2 KiB
HTML

<!DOCTYPE HTML>
<html>
<body>
<head><meta charset="utf-8"></head>
<form name="upload">
<input type="file" name="myfile">
<input type="submit" value="Загрузить">
</form>
<div id="log">Прогресс загрузки</div>
<script>
function log(html) {
document.getElementById('log').innerHTML = html;
}
function onSuccess() {
log('success');
}
function onError() {
log('error');
}
function onProgress(loaded, total) {
log(loaded + ' / '+ total);
}
document.forms.upload.onsubmit = function() {
var file = this.elements.myfile.files[0];
if (file) {
upload(file);
}
return false;
}
function upload(file) {
var xhr = new XMLHttpRequest();
// обработчики можно объединить в один,
// если status == 200, то это успех, иначе ошибка
xhr.onload = xhr.onerror = function() {
if(this.status == 200) {
log("success");
} else {
log("error " + this.status);
}
};
// обработчик для закачки
xhr.upload.onprogress = function(event) {
log(event.loaded + ' / '+ event.total);
}
xhr.open("POST", "upload", true);
xhr.send(file);
}
</script>
</body>
</html>