下载第三方插件:
在www.npmjs.com中下载formidable模块
表单代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:81/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="file" name="tupian"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
加载第三方代码接收文件数据:
var http = require("http");
var formidable = require('formidable');
var fs = require("fs");
var sd = require("silly-datetime");
var path = require("path");
//创建服务器
http.createServer(function (req, res) {
//如果你访问地址是这个,并且请求类型是post
if(req.url == "/dopost" && req.method.toLowerCase() == "post"){
var alldata = "";
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = "./uploads";
//执行里面的回调函数的时候,表单已经全部接受完毕了
form.parse(req, function(err, fields, files) {
if(err){
throw err;
}
//时间
var ttt = sd.format(new Date(), 'YYYYMMDDHHmmss');
var ran = parseInt(Math.random() * 89999 + 10000);
var extname = path.extname(files.tupian.name);
var oldpath = __dirname + "/" + files.tupian.path;
var newpath = __dirname + "/uploads/" + ttt + ran + extname;
//改名
fs.rename(oldpath, newpath, function () {
if(err){
throw Error("改名失败");
}
//所有的文本域、单选框,都在fields存放。所有的文本域都在files存放
res.writeHead(200, {'content-type': 'text/plain; charset=utf-8'});
res.end("成功");
});
});
} else if(req.url == "/"){
fs.readFile("./aa.html", function (err, data) {
res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});
res.end(data);
});
} else {
res.writeHead(404, {'content-type': 'text/html; charset=utf-8'});
res.end("路径错了");
}
}).listen(81, "127.0.0.1");