🧰 Node.js File & Server Operations
Estimated reading: 3 minutes 32 views

⬆️ Node.js – Uploading Files – Handle File Uploads with formidable and multer


🧲 Introduction – How File Uploads Work in Node.js?

File uploading is a common requirement in modern web applications, from profile pictures to documents and media files. In Node.js, file uploads are not handled natively—you must use middleware or external libraries like formidable (built-in with minimal apps) or multer (commonly used with Express).

🎯 In this guide, you’ll learn:

  • How file uploads work with formidable and multer
  • Upload files through HTML forms
  • Store files locally with example directory structure
  • Best practices for validating and storing uploads securely

💼 Method 1 – Uploading Files Using formidable (No Express Needed)

✅ Install formidable:

npm install formidable

📁 HTML Upload Form (upload.html):

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" />
  <input type="submit" value="Upload File" />
</form>

🧪 Node.js Server with formidable:

const http = require('http');
const fs = require('fs');
const formidable = require('formidable');

http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm({ uploadDir: 'uploads', keepExtensions: true });

    form.parse(req, (err, fields, files) => {
      if (err) throw err;
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('File uploaded successfully');
    });
  } else {
    fs.readFile('upload.html', (err, data) => {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    });
  }
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

📂 Uploaded files are stored in the uploads/ directory.


🧰 Method 2 – Uploading Files Using multer (with Express)

✅ Install multer and express:

npm install express multer

🧪 Create Express Upload Server:

const express = require('express');
const multer = require('multer');
const app = express();

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads'),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});

const upload = multer({ storage });

app.post('/upload', upload.single('fileToUpload'), (req, res) => {
  res.send('File uploaded using multer!');
});

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/upload.html');
});

app.listen(3000, () => console.log('Listening on port 3000'));

🧪 Use same upload.html form as before.

📂 Uploaded file is stored in /uploads with a timestamped filename.


🔐 File Upload Security & Validation Tips

✅ Practice🔒 Why It’s Important
Set max file sizePrevent denial of service (DoS) attacks
Restrict file typesPrevent uploads of .exe, .php, etc.
Sanitize file namesAvoid overwriting and path traversal
Store outside public folderPrevent direct file execution via URL
Use HTTPSSecure file transfer over network

📌 Summary – Recap & Next Steps

Node.js can handle file uploads efficiently using modules like formidable for basic apps and multer for Express-based APIs. Both methods allow secure, fast handling of uploaded files with various customizations.

🔍 Key Takeaways:

  • Use formidable for vanilla Node.js apps
  • Use multer with Express for API-based uploads
  • Always validate, sanitize, and secure uploads
  • Store files in separate folders and monitor upload size/type

⚙️ Real-world relevance:
Used in CMS, profile systems, cloud storage apps, image hosting platforms, and admin dashboards.


❓FAQs – Node.js File Uploading


Which module is better: formidable or multer?
✅ Use formidable for non-Express apps. Use multer for Express apps—it’s more customizable.


How can I upload multiple files in Node.js?
✅ Use upload.array('files', 5) in multer, or handle multiple fields using formidable.


Where are uploaded files stored by default?
✅ Both libraries store files locally in the uploads/ directory unless reconfigured.


How do I handle file size limits with multer?
✅ Pass limits option:

multer({ limits: { fileSize: 2 * 1024 * 1024 } })  // 2MB

Can I store uploads in cloud services (e.g., AWS S3)?
✅ Yes. Multer supports custom storage engines like multer-s3 for S3 integration.


Share Now :

Leave a Reply

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

Share

⬆️ Node.js – Uploading Files

Or Copy Link

CONTENTS
Scroll to Top