- 多文件传输
<div>
<h2>多文件上传</h2>
<input type="file" id="f1" name="file" multiple />
<button type="button" id="btn-submit">上传</button>
</div>
<script>
var btn = document.getElementById('btn-submit')
btn.addEventListener('click', submitUpload)
function submitUpload() {
var files = document.getElementById('f1').files
if (!files.length) {
console.log('请选择上传的文件')
return
}
var fd = new FormData()
for (let i = 0; i < files.length; i++) {
fd.append('file', files[i])
}
var xhr = new XMLHttpRequest()
var url = 'http://localhost:9000/upload'
xhr.open('POST', url, true)
xhr.send(fd)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = JSON.parse(xhr.responseText)
console.log(res)
}
}
}
</script>
- 带进度条的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>上传文件</title>
<style>
#progress {
height: 20px;
width: 300px;
margin-bottom: 30px;
}
#progress span {
display: block;
height: 20px;
width: 0;
color: #fff;
font-size: 12px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
</style>
</head>
<body>
<div>
<h2>多文件上传</h2>
<input type="file" id="f1" name="file" multiple />
<div id="progress">
<span class="red"></span>
</div>
<button type="button" id="btn-submit">上传</button>
</div>
<script>
var btn = document.getElementById('btn-submit')
btn.addEventListener('click', submitUpload)
function submitUpload() {
var progressSpan = document.getElementById('progress').firstElementChild
progressSpan.style.width = '0'
progressSpan.classList.remove('green')
var files = document.getElementById('f1').files
if (!files.length) {
console.log('请选择上传的文件')
return
}
var fd = new FormData()
for (let i = 0; i < files.length; i++) {
fd.append('file', files[i])
}
var xhr = new XMLHttpRequest()
var url = 'http://localhost:9000/upload'
xhr.open('POST', url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = JSON.parse(xhr.responseText)
console.log(res)
}
}
xhr.onprogress = updateProgress
xhr.upload.onprogress = updateProgress
function updateProgress(event) {
if (event.lengthComputable) {
console.log(event.loaded)
var completedPercent = ((event.loaded / event.total) * 100).toFixed(
2
)
progressSpan.style.width = completedPercent + '%'
progressSpan.innerHTML = completedPercent + '%'
if (completedPercent > 90) {
progressSpan.classList.add('green')
}
console.log('已上传', completedPercent)
}
}
xhr.send(fd)
}
</script>
</body>
</html>