html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#filebox {
width: 300px;
line-height: 150px;
text-align: center;
background-color: #bfc;
margin: 100px auto;
}
#progress-wrapper {
margin: 0 auto;
width: 300px;
height: 30px;
border: 1px solid #bfa;
}
#progress {
height: 100%;
width: 0;
background-color: #bfa;
}
</style>
<body>
<div id="filebox">拖入文件进行上传</div>
<div id="progress-wrapper">
<div id="progress"></div>
</div>
<script>
let filebox = document.getElementById('filebox');
filebox.addEventListener('dragenter', function (ev) {
this.innerText = '松手上传'
}, false);
filebox.addEventListener('dragleave', function (ev) {
this.innerText = '拖入文件进行上传';
}, false);
//ondragover不阻止默认时间,ondrop不会触发
filebox.addEventListener('dragover', function (ev) {
ev.preventDefault();
})
filebox.addEventListener('drop', function (ev) {
ev.preventDefault();
let data = new FormData();
Array.from(ev.dataTransfer.files).forEach(file => {
data.append('f1', file);
})
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/api', true);
let progress = document.getElementById('progress');
xhr.upload.onprogress = function (e) {
let percent = e.loaded / e.total * 100 + '%';
progress.style.width = percent;
}
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
alert('成功');
} else {
alert('失败');
}
}
}
}, false)
</script>
</body>
</html>
为了方便 后端用了express+multer
let multerObj = multer({ dest: './upload' })
server.use(multerObj.any())
server.use('/api', (req, res) => {
console.log(req.method);
if (req.headers['origin'] == 'null' || req.headers['origin'].startsWith('http://localhost')) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
res.send("OK");
})
server.use(express.static('./static'))
网友评论