步骤:
1、完成通过form表单发送普通的POST请求
1.1、开启web服务,让浏览器访问的时候,给它返回一个form表单的页面
1.2、后台进行处理
2、完成通过form表单发送文件上传的POST请求
1.1、在项目根目录生成一个package.json的文件,它有一个作用,就是记录我们安装过哪些第三方包
切换到项目根目录,但是项目名称不能是中文,执行 npm init -y
1.2、安装 multiparty 这个第三方包
切换到项目根目录,使用 npm i multiparty -S/--save
1.3、根据第三方包的文档,写代码(拷贝代码)
1.4、对我们上传的文件名称进行重新命名
我们约定,我们的文件名称就命令成年月日时分秒毫秒
安装 date-format npm i date-format -S
// 1. 导入http模块
const http = require('http')
const fs = require('fs')
const path = require('path')
const querystring = require('querystring')
const util = require('util')
const multiparty = require('multiparty')
const format = require('date-format');
// 2. 创建server
http
.createServer(function(req,res) {
if (req.url.includes('index')) {
const filePath = path.join(__dirname,'index.html')
const htmlBuffer = fs.readFileSync(filePath)
res.setHeader('Content-Type','text/html;charset=utf-8')
res.end(htmlBuffer)
}else if(req.url.includes('upload')) {
// 对上传过来的请求数据,进行处理,会创建文件夹
const dirPath = path.join(__dirname,'upload')
const exists = fs.existsSync(dirPath)
if(!exists) {
const err = fs.mkdirSync(dirPath)
if (err) {
console.log(err)
}
console.log('mkdir OK')
}
// 创建form表单对象
var form = new multiparty.Form({
uploadDir:dirPath 将文件存在文件夹里面
})
form.parse(req, function(err, fields, files) {
console.log(fields);
Object.keys(fields).forEach(function(name) {
console.log(`${name} is ${fields[name][0]}`);
});
Object.keys(files).forEach(function(name) {
console.log(name);
const file=files[name][0]
const oldPath=file.path;
const newPath=path.join(__dirname,'upload',`${format('yyyyMMddhhmmssSSS',new Date())}.txt`)
const err=fs.renameSync(oldPath,newPath)
if(err){
console.log(err);
}
console.log('rename ok');
});
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
})
}
})
.listen(80,function() {
console.log('running...')
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
</style>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit" value="提交">
</form>
</body>
</html>