-
-
Save tejasrsuthar/8df5174c8f2bf831538c43b0e6013255 to your computer and use it in GitHub Desktop.
// Include Main HTTP module | |
var http = require('http'); | |
// Include Formidable libarary for Upload Processing | |
var formidable = require('formidable'); | |
// Include file system module | |
var fs = require('fs'); | |
// Create server for listening incoming connections | |
http.createServer(function (req, res) { | |
// File upload check with requested url | |
if (req.url == '/fileupload') { | |
// Create form object with formidable | |
var form = new formidable.IncomingForm(); | |
// Parse the form | |
form.parse(req, function (err, fields, files) { | |
// Get old file path | |
var oldpath = files.filetoupload.path; | |
// Set new file path | |
var newpath = 'C:/Users/Your Name/' + files.filetoupload.name; | |
// Move file from old path to new path | |
fs.rename(oldpath, newpath, function (err) { | |
// If any error then, throw it | |
if (err) throw err; | |
// Successfull confirmation | |
res.write('File uploaded and moved!'); | |
res.end(); | |
}); | |
}); | |
} else { | |
// Set header to text/html | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
// Write response with file upload form | |
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); | |
res.write('<input type="file" name="filetoupload"><br>'); | |
res.write('<input type="submit" name="submitNodeJSUploader">'); | |
res.write('</form>'); | |
return res.end(); | |
} | |
}).listen(8080); |
use:
var oldpath = files.fileupload.path;
to see all the attributes you can use:
var util = require('util');
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
res.end(util.inspect({fields: fields, files: files}));
On the util inspect i got to know that, the uploaded file details became JSON object conatiaing an array named as 'PersistentFile' in this it contains filepath, originalFilename, etc., to access it I use:
var form = new formidable.IncomingForm();
form.parse( req, function(err, fields, files) {
var oldPath = files.fileUpload[0].filepath;
});
The property fileUpload contains capital 'U" and in it the 'PersistentFile' is an array at location zero (0).
The originalFilename, size, _event, hashAlgorithm, filepath, newFilename, mimeType, etc.,
//The above code works for me.
var oldpath = files.filetoUpload.path;
TypeError: Cannot read property 'path' of undefined