File Upload API Documentation using NestJS
Overview
This guide provides detailed instructions for implementing a file upload API using NestJS. The architecture consists of three key files:
-
file.module.ts: Manages module configuration and imports necessary dependencies. -
file.controller.ts: Defines controller logic for processing file upload requests. -
file.service.ts: Encapsulates core file upload business logic within the service layer.
Step-by-Step Implementation
1. Create file.module.ts:
// file.module.ts import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { FileController } from './file.controller'; import { FileService } from './file.service'; @Module({ imports: [ MulterModule.register({ dest: './uploads' }), // Configure file storage location ], controllers: [FileController], providers: [FileService], exports: [FileService], // Make FileService available to other modules }) export class FileModule {} Explanation:
- This module imports
MulterModulefor file upload handling, configuring the storage destination (./uploads). - It registers the
FileControllerandFileService, exporting the latter for wider access.
2. Create file.controller.ts:
// file.controller.ts import { Post, UseInterceptors, UploadedFile, Controller } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { FileService } from './file.service'; @Controller('file') // Base route for file-related operations export class FileController { constructor(private readonly fileService: FileService) {} @Post('upload') // Endpoint for uploading files @UseInterceptors(FileInterceptor('file')) // Intercept and handle file uploads async uploadFile(@UploadedFile() file: Express.Multer.File) { // Delegate file handling to the FileService return await this.fileService.uploadFile(file); } } Explanation:
- This controller defines a
POSTendpoint (/file/upload) for file uploads. - The
@UseInterceptorsdecorator employsFileInterceptorto intercept incoming files. - The
@UploadedFiledecorator injects the uploaded file data into theuploadFilemethod. - The
uploadFilemethod calls the corresponding service method for further processing.
3. Create file.service.ts:
// file.service.ts import { Injectable } from '@nestjs/common'; import { Express } from 'express'; @Injectable() export class FileService { async uploadFile(file: Express.Multer.File) { // Add your specific file upload logic here, including: // 1. Validation (e.g., file size, type, MIME type) // ... // 2. Custom filename generation (optional) // ... // 3. Advanced storage logic (optional) // ... // 4. Return relevant information or perform further actions return { originalname: file.originalname, filename: file.filename, size: file.size, mimetype: file.mimetype, }; } } Explanation:
- This service contains the
uploadFilemethod, responsible for core file upload logic. - You'll implement essential steps like:
- Validation: Enforce file size, type, MIME type restrictions.
- Custom filename generation: (Optional) Create unique filenames.
- Advanced storage logic: (Optional) Utilize
diskStoragefrom Multer for more granular control. - Returning information/performing actions: Return details about the uploaded file or execute further actions based on the upload.
Additional Notes:
- Adjust import paths within files to match your project structure.
- Implement robust error handling and validation for various upload scenarios.
- Customize the file storage location and filename generation process.
- Consider integration with cloud storage solutions for scalability and redundancy.
- Thoroughly test your API with diverse file types, sizes, and edge cases.
Using the API:
- Install NestJS and necessary dependencies (refer to your project's requirements).
- Create the
file.module.ts,file.controller.ts, andfile.service.tsfiles with the provided code (adapted to your project). - Run your NestJS application.
- Use tools like Postman or curl to test the API:
- Endpoint:
POST http://localhost:3000/file/upload - Body: Use
form-dataand include a file with the field namefile. - Expected Response: Details about the uploaded file or the result of additional actions.
- Endpoint:
Testing the API using Postman:
Install Postman:
If you don't have Postman installed, download and install it from Postman's official website.
Run Your NestJS Application:
Ensure that your NestJS application is up and running.
Open Postman:
Open the Postman application.
Create a New Request:
- Click on the "New" button to create a new request.
- Choose a request type (e.g.,
POST) and enter the API endpoint:http://localhost:3000/file/upload.
Configure the Request:
- Select the
Bodytab. - Choose
form-dataas the body type. - Add a key-value pair with the key
fileand select a file to upload.
Send the Request:
- Click the "Send" button to send the request.
- Observe the response in the Postman console.
Verify the Response:
- Check the response for details about the uploaded file or any additional actions performed by the API.
Top comments (0)