How to handle file upload in Node.js ?
Last Updated :
02 Aug, 2024
File upload can easily be done by using Formidable. Formidable is a module that we can install on our project directory by typing the command
npm install formidable
Approach: We have to set up a server using the HTTPS module, make a form that is used to upload files, save the uploaded file into a temporary location by using the Formidable module & finally move that file into our project folder by using File System Module.
Step 1: Require HTTP, Formidable & File System Module
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
Step 2: Create a form for file upload
http.createServer((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"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(3000);
Step 3: Upload the file to the temporary folder using the Formidable Module
We have to create a variable for handling Incoming Form Data, then we will parse the data. We will also use the files parameter for getting the details regarding the uploaded file. Such as filepath is used to get the path of the file which is temporarily stored by Formidable Module, originalFilename which is used to get the actual file name of the uploaded file.
// Access the first file in the array
var uploadedFile = files.filetoupload[0];
var tempFilePath = uploadedFile.filepath;
var originalFilename = uploadedFile.originalFilename;
// Target file path
var projectFilePath = path.join(__dirname, 'uploaded_files', originalFilename);
// Ensure the upload directory exists
if (!fs.existsSync(path.join(__dirname, 'uploaded_files'))) {
fs.mkdirSync(path.join(__dirname, 'uploaded_files'));
}
Step 4: Move the uploaded file into the project folder
fs.rename(tempFilePath, projectFilePath, function (err) {
if (err) throw err;
res.write('File has been successfully uploaded');
res.end();
});
Node
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
// Create a server
http.createServer(function (req, res) {
if (req.url == '/fileupload' && req.method.toLowerCase() === 'post') {
// Initialize formidable
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
if (err) {
res.writeHead(400, {'content-type': 'text/plain'});
res.write('Error processing the file upload.');
res.end();
return;
}
// Log the files object to inspect its structure
console.log(files);
// Access the first file in the array
var uploadedFile = files.filetoupload[0];
var tempFilePath = uploadedFile.filepath;
var originalFilename = uploadedFile.originalFilename;
// Target file path
var projectFilePath = path.join(__dirname, 'uploaded_files', originalFilename);
// Ensure the upload directory exists
if (!fs.existsSync(path.join(__dirname, 'uploaded_files'))) {
fs.mkdirSync(path.join(__dirname, 'uploaded_files'));
}
// Rename and move the file
fs.rename(tempFilePath, projectFilePath, function (err) {
if (err) {
res.writeHead(500, {'content-type': 'text/plain'});
res.write('Error saving the file.');
res.end();
return;
}
res.writeHead(200, {'content-type': 'text/html'});
res.write('File has been successfully uploaded');
res.end();
});
});
} else {
// Serve the file upload form
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"><br>');
res.write('<input type="submit">');
res.write('</form>');
res.end();
}
}).listen(3000, () => {
console.log('Server is listening on port 3000');
});
Step to run the application: Open the terminal and type the following command.
node app.js
Output: