How to Upload Files in Node.js

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

Leave a Comment

Your email address will not be published. Required fields are marked *

中文 EN
🚀

RedGate VPN

免费节点太挤太慢?
升级高速稳定专线

立即体验 →

告别卡顿

RedGate VPN
全球高速节点

免费下载 →
Scroll to Top