File Upload (Cloudinary)
The File Upload component provides a standardized way to handle file uploads in Servercn using Cloudinary as the storage provider.
It abstracts common concerns such as multipart handling, Cloudinary configuration, and secure uploads, while integrating cleanly with the rest of the Servercn backend utilities.
Official Cloudinary Documentation, Cloudinary Node.js SDK
Features
- Cloudinary-backed file storage
- Supports images, videos, and raw files
- Secure server-side uploads
- Express-compatible middleware
- Works seamlessly with
ApiError,AsyncHandler, and middleware
Installation Guide
This component requires additional Servercn components.
npx servercn-cli add file-uploadYou will be prompted to select a file upload provider:
The CLI will then automatically configure the component based on your selected provider.
Prerequisites
You must have a Cloudinary account. Click here if you don't have one.
Define the following environment variables:
Ensure the following configuration is defined:
MVC: src/configs/env.ts
Feature: src/shared/configs/env.ts
Basic Implementation
1. Cloudinary Configuration
Create a Cloudinary configuration file:
MVC: src/configs/cloudinary.ts
Feature: src/shared/configs/cloudinary.ts
2. Upload Middleware
Servercn uses multer to handle multipart file uploads.
MVC: src/middlewares/upload-file.ts
Feature: src/shared/middlewares/upload-file.ts
3. Cloudinary Services
Services for uploading files to Cloudinary and deleting files from Cloudinary.
MVC: src/services/cloudinary.service.ts or src/utils/cloudinary.ts
Feature: src/modules/upload/upload.service.ts
Usage Example
1. Setup controllers
MVC: src/controllers/upload.controller.ts
Feature: src/modules/upload/upload.controller.ts
2. Setup routes
MVC: src/routes/upload.routes.ts
Feature: src/modules/upload/upload.routes.ts
src/app.ts
Security Best Practices
- Enforce file size limits
- Validate MIME types when required
- Use private folders for sensitive uploads
- Never expose Cloudinary API keys/secrets to the client
- Prefer authenticated routes for uploads
- Use environment variables for all sensitive configuration