var http = require('http');
//读取内容借助模块
var fs = require('fs');
const formidable = require('formidable');
var util = require('util');
var server = http.createServer(function(req,res){
if(req.method.toLowerCase()=='get'&&req.url=='/form'){
fs.readFile('./form.html',function(err,data){
if(err){
res.statusCode == 404;
res.end('not found');
}
//返回html文件内容
res.statusCode = 200;
res.end(data);
});
}
if(req.method.toLowerCase()=='post'&&req.url=='/form'){
var form = formidable({ multiples: true });
//文件上传路径
form.uploadDir = './uploads';
//保持文件名
form.keepExtensions = true;
form.parse(req,function(err,fields,files){
res.writeHead(200,{'content-type':"text/plain"});
res.write('receives upload:
');
res.end(util.inspect({fields:fields,files:files}));
});
}
});
server.listen(8084);
html部分
<html>
<meta charset="utf-8">
<time>上传</time>
<body>
<form action="/form" method="post"
enctype="multipart/form-data">
用户名<input type="text" name="username"><br/>
密码<input type="password" name="password"><br/>
<label for="file">头像:</label><br/>
<input type="file" name="file" id="file" />
<br /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>