在JavaScript中实现图片上传并显示进度条,主要涉及以下几个概念:
loadstart
, progress
, load
, loadend
等,可以用来更新进度条。以下是一个简单的示例,展示如何使用JavaScript实现图片上传并显示进度条:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传进度条</title>
<style>
#progressBar {
width: 100%;
background-color: #ddd;
}
#progress {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
</style>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadFile()">上传图片</button>
<div id="progressBar">
<div id="progress"></div>
</div>
<script>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const xhr = new XMLHttpRequest();
const progressBar = document.getElementById('progress');
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
progressBar.style.width = percentComplete + '%';
progressBar.textContent = percentComplete.toFixed(2) + '%';
}
});
xhr.open('POST', '/upload', true);
xhr.send(file);
}
</script>
</body>
</html>
问题1:进度条不更新
问题2:上传过程中页面卡顿
问题3:跨域问题
通过以上方法,可以有效地解决JavaScript上传图片时显示进度条的相关问题。
没有搜到相关的文章