forked from gongruixue/file-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
42 lines (38 loc) · 1.14 KB
/
server.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
var http = require('http'),
path = require('path'),
formidable = require('formidable'),
mkdirp = require('mkdirp');
var server = http.createServer(function(req, res){
function onError(msg){
res.statusCode = 500;
res.statusMessage = msg;
res.end();
}
function onSuccess(){
res.end();
}
if(req.url == '/receiver' && req.method.toLowerCase() == 'post'){
var form = new formidable.IncomingForm();
var to = '';
form.on('field', function onField(name, value){
if(name == 'to'){
to = value;
form.removeListener('field', onField);
}
});
form.on('fileBegin', function(name, file){
try{
mkdirp.sync(path.dirname(to));
file.path = to;
}catch(e){
onError('cannot make dir ' + to + ' to save file ' + name);
form.emit('aborted');
}
});
form.parse(req, function(err, fields, file){
if(err) onError(err.message);
else onSuccess();
});
}
});
module.exports = server;