Skip to content

Instantly share code, notes, and snippets.

@tejasrsuthar
Last active September 4, 2023 18:38
Show Gist options
  • Save tejasrsuthar/8df5174c8f2bf831538c43b0e6013255 to your computer and use it in GitHub Desktop.
Save tejasrsuthar/8df5174c8f2bf831538c43b0e6013255 to your computer and use it in GitHub Desktop.
Node JS File Upload with Formidable Module
// 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);
@xeroxstar
Copy link

var oldpath = files.filetoUpload.path;
TypeError: Cannot read property 'path' of undefined

@flavluc
Copy link

flavluc commented Aug 29, 2018

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}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment