input file 获取文件进度
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<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;
width: 0;
}
</style>
</head>
<body>
<input type="file" id="files" name="file" />
<button onclick="abortRead();">取消读取</button>
<div id="progress_bar">
<div class="percent">0%</div>
</div>
</body>
<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>
</html>