问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
<!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>Document</title>
<style>
.container {
padding-top: 60px;
}
.padding {
padding: 5px 0 20px 0;
}
.progress {
width: 800px;
height: 20px;
border: 1px solid #F4F4F4;
background-color: #F4F4F4;
}
.progress-bar {
text-align: center;
color: #fff;
background-color: #2E77BD;
}
</style>
</head>
<body>
<div class="container">
<div class="form-group">
<h2>请选择文件</h2>
<input type="file" id="file">
<br>
<div class="progress">
<div class="progress-bar" style="width:60%;">60%</div>
</div>
</div>
</div>
<script>
// 获取文件选择控件
var file = document.getElementById("file");
file.onchange = function() {
// 创建空的formData表单对象
var formData = new FormData();
// 将用户选择的文件追加到formData表单对象中
formData.append('attrName', this.files[0]);
//创建Ajax对象
var xhr = new XMLHttpRequest();
//加上下面xhr.upload.onprogress这一段代码就会报错,注释掉就不会
xhr.upload.onprogress = function(e) {
console.log(e);
}
// 对Ajax对象进行配置
xhr.open('post', 'http://localhost:3000/upload2');
// 发送ajax请求
xhr.send(formData);
// 监听服务器端响应给客户端的数据
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
</script>
</body>
</html>
js文件中
app.post('/upload2', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
const form = new formidable.IncomingForm({ multiples: true, uploadDir: path.join(__dirname, 'formData', 'uploads'), keepExtensions: true });
form.parse(req, (err, fields, files) => {
res.send('ok');
});
});