File Upload (ImageKit)
The File Upload component provides a standardized way to handle file uploads in ServerCN using ImageKit as the storage provider.
It abstracts common concerns such as multipart handling, ImageKit configuration, and secure uploads, while integrating cleanly with the rest of the ServerCN backend utilities.
Official ImageKit Documentation, ImageKit Node.js SDK
Features
- ImageKit-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.
๐ You do not need to install any ServerCN components manually. Running this component installer will automatically install all required components. Manual installation is optional and only recommended if you prefer fine-grained components control
1. Install ServerCN components(Optional)
2. Install this component
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 an ImageKit 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. ImageKit Configuration
Create an ImageKit configuration file:
MVC: src/configs/imagekit.ts
Feature: src/shared/configs/imagekit.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. ImageKit Services
Services for uploading files to ImageKit and deleting files from ImageKit.
MVC: src/services/upload.service.ts or src/utils/imagekit.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 ImageKit private keys to the client
- Prefer authenticated routes for uploads
- Use environment variables for all sensitive configuration