Skip to contentPedro Farbo
Lesson 14 / 2550 min

File Upload

File Upload

Handle file uploads locally and to S3.

Installation

bash
npm install multernpm install -D @types/multer

Local Upload

typescript
// src/config/upload.tsimport multer from 'multer';import path from 'path';import { randomUUID } from 'crypto'; const storage = multer.diskStorage({  destination: (req, file, cb) => {    cb(null, path.resolve(__dirname, '..', '..', 'uploads'));  },  filename: (req, file, cb) => {    const ext = path.extname(file.originalname);    cb(null, `${randomUUID()}${ext}`);  },}); const fileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {  const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];   if (allowed.includes(file.mimetype)) {    cb(null, true);  } else {    cb(new Error('File type not allowed'));  }}; export const upload = multer({  storage,  fileFilter,  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB});

Upload Routes

typescript
// Single uploadrouter.post('/single', authenticate, upload.single('image'), (req, res) => {  if (!req.file) {    return res.status(400).json({ error: 'No file uploaded' });  }   res.json({    filename: req.file.filename,    path: `/uploads/${req.file.filename}`,  });}); // Multiple uploadrouter.post('/multiple', authenticate, upload.array('images', 10), (req, res) => {  const files = req.files as Express.Multer.File[];  res.json(files.map(f => ({ filename: f.filename })));});

AWS S3 Upload

bash
npm install @aws-sdk/client-s3
typescript
// src/services/storage.service.tsimport { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';import { randomUUID } from 'crypto'; const s3 = new S3Client({  region: process.env.AWS_REGION!,  credentials: {    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,  },}); export class StorageService {  async upload(file: Express.Multer.File, folder: string = 'uploads'): Promise<string> {    const key = `${folder}/${randomUUID()}.${file.originalname.split('.').pop()}`;     await s3.send(new PutObjectCommand({      Bucket: process.env.AWS_S3_BUCKET!,      Key: key,      Body: file.buffer,      ContentType: file.mimetype,    }));     return `https://${process.env.AWS_S3_BUCKET}.s3.amazonaws.com/${key}`;  }}

Summary

  • ✅ Local upload with Multer
  • ✅ File validation
  • ✅ S3 cloud upload

Next lesson: Sending Emails! 🚀

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e