Skip to content

Instantly share code, notes, and snippets.

@kuanyingchou
Created July 28, 2014 08:22
Show Gist options
  • Save kuanyingchou/87d9729cc0e4fab37839 to your computer and use it in GitHub Desktop.
Save kuanyingchou/87d9729cc0e4fab37839 to your computer and use it in GitHub Desktop.
//modified from https://github.com/felixge/node-formidable
var UPLOAD_DIR = "./";
var PORT = 8000;
var formidable = require('formidable'),
http = require('http'),
util = require('util');
var server = http.createServer(function(req, res) {
switch(req.url) {
case "/":
showUploadForm(req, res);
break;
case "/upload":
handleUpload(req, res);
break;
}
})
function showUploadForm(req, res) {
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}
function handleUpload(req, res) {
if (req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = UPLOAD_DIR;
form.on('fileBegin', function(name, file) {
file.path = form.uploadDir + "/" + file.name;
})
.on('error', function(err) {
throw err;
});
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
}
}
server.listen(PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment