node post请求
1 var alldata = ""; 2 //下面是post请求接收的一个公式 3 //node为了追求极致,它是一个小段一个小段接收的。 4 //接受了一小段,可能就给别人去服务了。防止一个过大的表单阻塞了整个进程 5 req.addListener("data",function(chunk){ 6 alldata += chunk; 7 }); 8 //全部传输完毕 9 req.addListener("end",function(){ 10 console.log(alldata.toString()); 11 res.end("success"); 12 }); |
原生写POST处理,比较复杂,要写两个监听。文件上传业务比较难写。
所以,用第三方模块。formidable。
只要涉及文件上传,那么form标签要加一个属性:
1 <form action="http://127.0.0.1/dopost" method="post"enctype="multipart/form-data"> |
/**
* 修改上传的文件名
*/
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){
//如果你的访问地址是这个,并且请求类型是post
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(util.inspect({fields: fields, files: files}));
//时间,使用了第三方模块,silly-datetime
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(err){
if(err){
throw Error("改名失败");
}
res.writeHead(200, {'content-type': 'text/plain'});
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(80,"192.168.41.36");