Created
October 29, 2014 09:48
-
-
Save roadmanfong/19eac03312e037e4155f to your computer and use it in GitHub Desktop.
node.js upload file
This file contains hidden or 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 formidable = require('formidable'), | |
http = require('http'), | |
util = require('util'), | |
fs = require('fs-extra'); | |
http.createServer(function(req, res) { | |
/* Process the form uploads */ | |
if (req.url == '/upload' && req.method.toLowerCase() == 'post') { | |
var form = new formidable.IncomingForm(); | |
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})); | |
}); | |
form.on('end', function(fields, files) { | |
/* Temporary location of our uploaded file */ | |
var temp_path = this.openedFiles[0].path; | |
/* The file name of the uploaded file */ | |
var file_name = this.openedFiles[0].name; | |
/* Location where we want to copy the uploaded file */ | |
var new_location = 'uploads/'; | |
fs.copy(temp_path, new_location + file_name, function(err) { | |
if (err) { | |
console.error(err); | |
} else { | |
console.log("success!") | |
} | |
}); | |
}); | |
return; | |
} | |
/* Display the 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