本地文件上传添加进度条和限制
1、上传本地文件时显示百分比的进度条。
2、文件未上传完成时,通过input标签的disabled属性禁止上传文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本地文件上传</title>
</head>
<body>
<div class="upload">
<input type="file" id="uploadFile" class="hidden-input"/>
<label for="uploadFile" class="upload-label">
<span>选择文件</span>
<div class="progress-bar">
<div class="progress"></div>
<div class="progress-text"></div>
</div>
</label>
</div>
</body>
<style type="text/css">
.upload {
display: inline-block;
position: relative;
}
.hidden-input{
display: none;
}
.upload-label {
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 40px;
padding: 10px 20px;
background-color: indianred;
color: white;
font-weight: 600;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
cursor: pointer;
transition: background-color 0.5s;
}
.progress-bar {
position: absolute;
bottom: -20px;
left: 0;
width: 100%;
height: 20px;
background-color: #ccc;
}
.progress {
height: 100%;
width: 0;
background-color: royalblue;
}
.progress-text {
position: absolute;
width: 100%;
bottom: 0px;
text-align: center;
font-size: 16px;
font-weight: bold;
color: white;
}
</style>
<script type="text/javascript">
var uploadInput = document.getElementById("uploadFile");
var uploadLabel = document.querySelector(".upload-label");
var progressBar = document.querySelector(".progress");
var progressText = document.querySelector(".progress-text");
uploadInput.addEventListener("change", function() {
progressBar.setAttribute("style", "transition: width 0s;width:0%")
setTimeout(() => {
var file = uploadInput.files[0];
if (file) {
uploadInput.disabled = true;
uploadLabel.setAttribute("style", "background-color: #999")
var reader = new FileReader();
progressBar.setAttribute("style", "transition: width 0.3s;width:0%")
reader.onprogress = function(event) { //文件上传过程,事件会在请求接收到数据的时候被周期性触发
if (event.lengthComputable) {
let percent = ((event.loaded / event.total) * 100).toFixed(2);
console.log("进度:", percent)
progressBar.style.width = percent + "%";
progressText.innerText = percent + "%";
}
}
reader.onloadend = function() { //资源加载进度停止之后被触发
progressBar.style.width = "100%";
progressText.innerText = 100 + "%";
setTimeout(() => {
progressBar.setAttribute("style", "transition: width 0s;width:100%");
uploadLabel.setAttribute("style", "background-color: indianred");
uploadInput.disabled = false;
}, 100)
};
reader.readAsDataURL(file);
}
})
});
</script>
</html>