input上传文件 显示进度条

<style>
#progress_bar {
margin: 10px 0;
padding: 3px;
border: 1px solid #000;
font-size: 14px;
clear: both;
opacity: 0;
-moz-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
opacity: 1.0;
}
#progress_bar .percent {
background-color: #99ccff;
height: auto;
 0;
}
</style>

我们在使用异步事件处理时还能顺便获得一项优势,那就是能够监控文件的读取进度;这对于读取大文件、查找错误和预测读取完成时间非常实用。

onloadstart 和 onprogress 事件可用于监控读取进度。

以下示例演示了如何通过显示进度条来监控读取状态。要查看进度指示器的实际效果,请尝试读取大文件或远程驱动器中的文件。

<input type="file" id="files" name="file" />
<button onclick="abortRead();">取消读取</button>
<div id="progress_bar"><div class="percent">0%</div></div>
<script>
var reader;
var progress = document.querySelector('.percent');

function abortRead() {
reader.abort();
}
// 文件上传出错后的函数
function errorHandler(e) {
switch(e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
alert('文件没找到');
break;
case e.target.error.NOT_READABLE_ERR:
alert('文件不可读');
break;
case e.target.error.ABORT_ERR:
break;
default:
alert('读取文件时出错');
};
}
// 更新进度条
function updateProgress(e) {
// e 是一个 ProgressEvent.
if (e.lengthComputable) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
// 更新进度条长度
if (percentLoaded < 100) {
progress.style.width = percentLoaded + '%';
progress.textContent = percentLoaded + '%';
}
}
}
// 选择上传文件后的方法
function handleFileSelect(e) {
// 在选择新文件后重置进度指示器
progress.style.width = '0%';
progress.textContent = '0%';

reader = new FileReader();
reader.onerror = errorHandler;
reader.onprogress = updateProgress;
reader.onabort = function(e) {
alert('已取消读取');
};
reader.onloadstart = function(e) {
document.getElementById('progress_bar').className = 'loading';
};
reader.onload = function(e) {
// 确保进度条最后显示100%
progress.style.width = '100%';
progress.textContent = '100%';
setTimeout("alert('文件已读取成功!')", 0);
}

// 将文件作为二进制字符串读入
reader.readAsBinaryString(e.target.files[0]);
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

————————————————
版权声明:本文为CSDN博主「艾欢欢」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/AiHuanhuan110/java/article/details/90607914

原文地址:https://www.cnblogs.com/wang-xx/p/12745169.html