混合表单的提交和后台的数据接受
- 前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="form-wrapper">
<div class="form-item">
<span>用户名</span>
<input name="username" type="text">
</div>
<div class="form-item">
<span>密码</span>
<input name="password" type="text">
</div>
<div class="form-item">
<span>头像</span>
<input type="file" name="avatar">
</div>
<div class="form-item">
<label>
<span>性别</span>
</label>
<input type="radio" name="sex" value="男">
<input type="radio" name="sex" value="女">
</div>
<div class="form-btn">
<button id="btn">提交</button>
</div>
</form>
<script src="./axios.min.js"></script>
<script>
window.onload = function () {
const btn = document.querySelector('#btn')
btn.addEventListener('click', function (e) {
e.preventDefault();
const formWrapper = document.querySelector('#form-wrapper')
const formData = new FormData(formWrapper); // 这里传入的是一个form节点
formData.append('address', '广东广州'); // 如果还有别的数据可以这样插入
axios.post('http://localhost:3001/files', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res.data)
})
})
}
</script>
</body>
</html>
- 后台代码
cnpm install multer body-parser --save-dev cnpm install express --save
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const multer = require('multer');
//设置跨域访问
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.use(bodyParser.urlencoded({ extended: false }));
let multerObj = multer({ dest: './uploads/' }) // 设置文件上传目录
app.use(multerObj.any());
app.post('/files', function (req, res) {
// req.files是一个数组,body表示普通数据,files表示文件数据
// console.log(req.body, req.files)
// 如果是图片,可以这样存储
let avatarUrl = ''
req.files.forEach(file => {
if (file.fieldname === 'avatar') { // avatar 就是前端存储头像的name字段
avatarUrl = file.filename // filename 就是对应要存到数据库的字段
}
})
const { username, password, sex } = req.body;
// user表
// insert into user(username, password, avatar_url, sex) values ('${username}', '${password}', '${avatar_url}', '${sex}')
res.send('ok')
})
// 静态文件映射
app.use(express.static('uploads/'))
app.listen(3001);