Node.js Files Upload using Formidable package
Generally, In web applications, users from client machine is required to upload file (such as the user uploading images and videos with Facebook , Instagram apps etc.) to the server. There are a number of open-source modules available on the NPM registry, with which the feature of uploading files can be enabled in a Node.js application. The formidable module offers a convenient API to handle the file uploads. The formidable module can be imported in a core Node.js module along with the built-in http module, as well as the Express app.
Formidable : The Formidable module is a fast and streaming multipart parser, capable of automatically writing file uploads to the disk. It has a low memory footprint, with efficient error handling mechanism.
As a first step, install the formidable module with the following command −
npm install formidable
In this example, usage of Formidable module in a node.js application that includes http module and in an ExpressJs application are shown below with Node.js http module
The following example calls the createServer() function to launch the Node.JS server and renders a multipart HTML form for the user to choose the file to be uploaded.
When the file is submitted, the form data is parsed and the uploaded file is copied in the default location in the disk.
var http = require('http');
var formidable = require('formidable');
var errors = formidable.formidableErrors;
const server = http.createServer(async (req, res) => {
if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') {
// parse a file upload
const form = new formidable.IncomingForm();
let fields;
let files;
try {
[fields, files] = await form.parse(req);
} catch (err) {
res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
res.end(String(err));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ fields, files }, null, 2));
return;
}
// show a file upload form
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h2>With Node.js <code>"http"</code> module and use of formidable package</h2>
<form action="/api/upload" enctype="multipart/form-data" method="post">
<div>Text field title: <input type="text" name="title" /></div>
<div>File: <input type="file" name="multipleFiles" multiple="multiple" /></div>
<input type="submit" value="Upload" />
</form>
`);
});
server.listen(5000, () => {
console.log('Server listening on http://localhost:5000/ ...');
});
As the application is run, the browser shows the following form to choose a file to be uploaded.
Nodejs http Module : After successful upload operation, the browser shows the following result
{
"fields": {
"title": [
"test"
]
},
"files": {
"multipleFiles": [
{
"size": 4203211,
"filepath": "C:\\Users\\user\\AppData\\Local\\Temp\\930f2f754006b790729e0d200",
"newFilename": "930f2f754006b790729e0d200",
"mimetype": "image/png",
"mtime": "2023-12-24T08:04:09.856Z",
"originalFilename": "1.png"
}
]
}
}
D:\React_Project\NodeProject> node formidabeExample.js
node:internal/modules/cjs/loader:1252
throw err;
^
Error: Cannot find module 'formidable'
Require stack:
- D:\React_Project\NodeProject\formidabeExample.js
at Function._resolveFilename (node:internal/modules/cjs/loader:1249:15)
at Function._load (node:internal/modules/cjs/loader:1075:27)
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:218:24)
at Module.require (node:internal/modules/cjs/loader:1340:12)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (D:\React_Project\NodeProject\formidabeExample.js:2:18)
at require (node:internal/modules/helpers:141:16)
at Object.<anonymous> (D:\React_Project\NodeProject\formidabeExample.js:2:18)
at Object.<anonymous> (D:\React_Project\NodeProject\formidabeExample.js:2:18)
at Module._compile (node:internal/modules/cjs/loader:1546:14)
at Object..js (node:internal/modules/cjs/loader:1689:10)
at Module.load (node:internal/modules/cjs/loader:1318:32) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'D:\\React_Project\\NodeProject\\formidabeExample.js' ]
}
Node.js v22.11.0
PS D:\React_Project\NodeProject> npm install formidable
added 6 packages in 3s
1 package is looking for funding
run `npm fund` for details
PS D:\React_Project\NodeProject> node formidabeExample.js
Server listening on http://localhost:5000/ ...
Using Express.js
The simplest usage of formidable module in an Express.JS code is below
import express from 'express';
import formidable from 'formidable';
const app = express();
app.get('/', (req, res) => {
res.send(`
<h2>Example With <code>"express"</code> npm package</h2>
<form action="/api/upload" enctype="multipart/form-data" method="post">
<div>File Type: <input type="text" name="title" /></div>
<div>File: <input type="file" name="someExpressFiles" multiple="multiple" /></div>
<input type="submit" value="Upload" />
</form>
`);
});
app.post('/api/upload', (req, res, next) => {
const form = formidable({});
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
res.json({ fields, files });
});
});
app.listen(5000, () => {
console.log('Server listening on http://localhost:5000 ...');
});
You can also install and use body-parser module to parse the multipart HTML form data in the uploading process.
D:\React_Project\NodeProject> node FormidableUsingExpress.js
node:internal/modules/esm/resolve:838
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), null);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'express' imported from D:\React_Project\NodeProject\FormidableUsingExpress.js
at packageResolve (node:internal/modules/esm/resolve:838:9)
at moduleResolve (node:internal/modules/esm/resolve:907:18)
at defaultResolve (node:internal/modules/esm/resolve:1037:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:650:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:599:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:582:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:241:38)
at ModuleJob._link (node:internal/modules/esm/module_job:132:49) {
code: 'ERR_MODULE_NOT_FOUND'
}
Node.js v22.11.0
PS D:\React_Project\NodeProject> npm install express
added 65 packages, and audited 72 packages in 4s
14 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
PS D:\React_Project\NodeProject> node FormidableUsingExpress.js
(node:33100) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///D:/React_Project/NodeProject/FormidableUsingExpress.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to D:\React_Project\NodeProject\package.json.
(Use `node --trace-warnings ...` to show where the warning was created)
Server listening on http://localhost:5000 ...
Output in browser
{
"fields": {
"title": [
"Pancard"
]
},
"files": {
"someExpressFiles": [
{
"size": 12887,
"filepath": "C:\\Users\\ANUJVE~1\\AppData\\Local\\Temp\\6dc28e70d6a5689f8b67f5200",
"newFilename": "6dc28e70d6a5689f8b67f5200",
"mimetype": "image/jpeg",
"mtime": "2023-11-30T04:19:13.184Z",
"originalFilename": "ang component.jpg"
}
]
}
}
Recent Comments