1. 普通的文本上传(通过原生form表单提交)
- 前端界面
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="/" method="post">
<label>
时间:
<input type="text" name="l_name">
</label>
<br>
<label>
地点:
<input type="text" name="l_address">
</label>
<br>
<label>
人物:
<input type="text" name="l_person">
</label>
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
- 服务器处理
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res, next) => {
res.render('index');
});
app.post('/', (req, res, next) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
})
req.on('end', () => {
fs.writeFile(path.join(__dirname, 'data.txt'), data, (err) => {
if (!err) {
res.end("success");
}
})
})
})
app.listen(2000, () => {
console.log("running");
});
服务器接收到数据后,以流的方式进行拼接,就可以获取到完整的数据。
2. 普通的文本上传(通过jQuery提交)
- 前端界面
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="http://localhost:2000/" method="post">
<label>
时间:
<input type="text" name="l_name">
</label>
<br>
<label>
地点:
<input type="text" name="l_address">
</label>
<br>
<label>
人物:
<input type="text" name="l_person">
</label>
<br>
<input id="btn_sub" type="button" value="提交">
</form>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script>
$('#btn_sub').on('click', function () {
var $form = $('form');
$.ajax({
url:$form.attr('action'),
type:$form.attr('method'),
// 数据序列化
data: $form.serialize(),
success: function (data) {
console.log(data);
}
})
// 阻止默认事件
return false;
});
</script>
</body>
</html>
- 服务器处理
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/node_modules', express.static(path.join(__dirname, '/node_modules')));
app.get('/', (req, res, next)=>{
res.render('index1');
});
app.post('/', (req, res, next)=>{
let data = '';
req.on('data', (chunk)=>{
data += chunk;
});
req.on('end', ()=>{
fs.writeFile(path.join(__dirname, 'data.txt'), data, (err)=>{
if(!err){
res.end('success!');
}
});
});
});
app.listen(2000, ()=>{
console.log('running!')
});
服务器端接收后,也是以流的方式进行接收
3. 文件上传(使用formidable)进行上传
具体实现:Node.js:借助formidable文件上传