Upload Files
Use formidable to upload files
C:UsersYour Name>npm install formidable
After the formidable file download is complete, you can then include this module in any program
var formidable = require('formidable');
Step 1 Create an upload form
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('
<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload">
');
res.write('<input type="submit">');
res.write('</form>
');
return res.end();
}).listen(8080);
Step 2 Parse the uploaded file
This powerful module can parse uploaded files as soon as they are uploaded to the server. When a file is uploaded and parsed, it will be placed in a temporary folder on your computer.
var http = require('http');
var formidable = require('formidable');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('
<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload">
');
res.write('<input type="submit">');
res.write('</form>
');
return res.end();
}
}).listen(8080);
Step 3
When a file is successfully uploaded to the server, it is placed in a temporary folder. The path to this directory can be found in the “files” object, passed as the third argument in the callback function of the parse() method. To move the file to a folder of your choice, use the file system module and rename the file:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('
<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload">
');
res.write('<input type="submit">');
res.write('</form>
');
return res.end();
}
}).listen(8080);