Created
January 12, 2018 13:42
-
-
Save abner/ab0cb98e2b063d65682129c426d4be48 to your computer and use it in GitHub Desktop.
Node Http File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var multiparty = require('multiparty'); | |
var http = require('http'); | |
var util = require('util'); | |
http | |
.createServer(function(req, res) { | |
if (req.url === '/upload' && req.method === 'POST') { | |
// parse a file upload | |
var form = new multiparty.Form(); | |
// parse sem a callback permite gerenciar o upload sem salvar em disco | |
// evitando que o conteúdo seja gravado em disco | |
// https://github.com/pillarjs/multiparty/issues/34#issuecomment-30359008 | |
// https://github.com/pillarjs/multiparty#formparserequest-cb | |
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, | |
p: JSON.stringify(files.p) | |
}) | |
); | |
}); | |
return; | |
} | |
// show a file upload form | |
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>' | |
); | |
}) | |
.listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment