0
0
Expressframework~5 mins

Why file upload handling matters in Express

Choose your learning style9 modes available
Introduction

File upload handling lets your app accept files from users safely and correctly. It helps keep your app secure and working well.

When users need to upload profile pictures or avatars.
When allowing users to submit documents or reports.
When building a form that accepts images or videos.
When storing user-generated content like PDFs or spreadsheets.
When you want to validate and control the size and type of uploaded files.
Syntax
Express
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('fileFieldName'), (req, res) => {
  // req.file contains the uploaded file info
  res.send('File uploaded!');
});

Use middleware like multer to handle file uploads in Express.

The upload.single('fileFieldName') middleware processes one file from the form field named fileFieldName.

Examples
Handles a single file upload from the form field named 'avatar'.
Express
app.post('/upload', upload.single('avatar'), (req, res) => {
  res.send(`Uploaded file: ${req.file.originalname}`);
});
Handles multiple file uploads (up to 3) from the form field named 'photos'.
Express
app.post('/photos', upload.array('photos', 3), (req, res) => {
  res.send(`Uploaded ${req.files.length} photos.`);
});
Customizes where and how files are saved on the server.
Express
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'custom_folder/'),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const uploadCustom = multer({ storage });

app.post('/custom-upload', uploadCustom.single('file'), (req, res) => {
  res.send('File saved with custom name and folder.');
});
Sample Program

This Express app uses multer to accept one file upload from the form field named 'file'. It saves the file in the 'uploads/' folder and responds with the original file name.

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

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

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  res.send(`File uploaded: ${req.file.originalname}`);
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});
OutputSuccess
Important Notes

Always validate file types and sizes to protect your app from harmful files.

Store uploaded files outside the public folder or use secure access controls.

Use descriptive error messages to help users understand upload issues.

Summary

File upload handling is essential for accepting user files safely.

Use middleware like multer in Express to manage uploads easily.

Always check and control uploaded files to keep your app secure.