Horje
How to Manage File Uploads in Node ?

Handling file uploads in NodeJS involves receiving files sent from a client-side form, processing them, storing them on the server, or performing additional operations such as validation and manipulation.

What is File Upload Handling?

File upload handling in NodeJS refers to the process of accepting files sent from a client-side application, typically through a form submission or an API endpoint. Once received, these files can be processed, stored, or manipulated according to the requirements of the application.

Why Handle File Uploads?

Handling file uploads is essential for many web applications that require users to upload files, such as images, documents, or multimedia content. Common use cases include uploading profile pictures, attaching files to messages, or uploading documents for processing.

How to Handle File Uploads in NodeJS:

File uploads in NodeJS can be handled using middleware such as multer or by directly parsing the incoming request stream. Here’s a basic example using multer middleware:

const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'),
(req, res) => {
// Handle uploaded file
const file = req.file;
if (!file) {
return res.status(400)
.send('No file uploaded.');
}
res.send('File uploaded successfully.');
});

app.listen(3000,
() => {
console.log('Server is running on port 3000');
});



Reffered: https://www.geeksforgeeks.org


Node.js

Related
Difference between res.send() and res.json() in Express Difference between res.send() and res.json() in Express
What is the os module in NodeJS used for? What is the os module in NodeJS used for?
How to create a simple HTTP server in Node ? How to create a simple HTTP server in Node ?
How to handle environment variables in Node ? How to handle environment variables in Node ?
What is the purpose of the path module in NodeJS? What is the purpose of the path module in NodeJS?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10