表单在form.html里面,发布在apache服务器中,通过http://localhost:8088/form.html来访问:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test post form</title>
</head>
<body>
<form action="http://localhost:3000/dopost" method="post" enctype="multipart/form-data">
<p>
姓名:<input type="text" name="name">
</p>
<p>
性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女
</p>
<p>
爱好:<input type="checkbox" name="likes" value="篮球">篮球
<input type="checkbox" name="likes" value="足球">足球
<input type="checkbox" name="likes" value="排球">排球
</p>
<p>
图片:<input type="file" name="tupian">
</p>
<p>
<input type="submit">
</p>
</form>
</body>
</html>
node服务器编写post.js:
var http = require("http");
var formidable = require('formidable');
var util = require("util");
var fs = require("fs");
var sd = require("silly-datetime");
var path = require("path");
var server = http.createServer(function(req,res){
if(req.url == "/dopost" && req.method.toLowerCase() == "post"){
//Creates a new incoming form.
var form = new formidable.IncomingForm();
//设置文件上传存放地址
form.uploadDir = "./uploads";
//执行里面的回调函数的时候,表单已经全部接收完毕了。
form.parse(req, function(err, fields, files) {
if(err){
throw err;
}
console.log(fields);
console.log(files);
//console.log(util.inspect({fields: fields, files: files}));
//时间,使用第三方模块,silly-datetime
var timestamp = sd.format(new Date(), 'YYYYMMDDHHmmss');
var rand = parseInt(Math.random() * 89999 + 10000);
var extname = path.extname(files.tupian.name);
//执行改名
var oldpath = __dirname + "/" + files.tupian.path;
//新的路径由三个部分组成:时间戳、随机数、拓展名
var newpath = __dirname + "/uploads/" + timestamp + rand + extname;
//改名
fs.rename(oldpath,newpath,function(err){
if(err){
throw Error("改名失败");
}
res.writeHead(200, {"Content-type":"text/html;charset=UTF-8"});
res.end("成功");
});
});
}else if(req.url == "/"){
//呈递form.html页面
fs.readFile("./form.html",function(err,data){
res.writeHead(200, {'content-type': 'text/html'});
res.end(data);
})
}else{
res.writeHead(404, {'content-type': 'text/html'});
res.end("404");
}
});
server.listen(3000,"localhost");
提交表单之后,成功结果: