-
Notifications
You must be signed in to change notification settings - Fork 4
/
13.js
57 lines (52 loc) · 1.99 KB
/
13.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Created by Danny on 2015/9/20 15:35.
*/
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");