Learn How to Create and Test a File Upload API using NestJS and Postman
Tags: node, nestjs, beginners, fileupload
Published: 2024-02-15 12:03:28

## 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`:**

```typescript
// 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 `MulterModule` for file upload handling, configuring the storage destination (`./uploads`).
- It registers the `FileController` and `FileService`, exporting the latter for wider access.

**2. Create `file.controller.ts`:**

```typescript
// 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 `POST` endpoint (`/file/upload`) for file uploads.
- The `@UseInterceptors` decorator employs `FileInterceptor` to intercept incoming files.
- The `@UploadedFile` decorator injects the uploaded file data into the `uploadFile` method.
- The `uploadFile` method calls the corresponding service method for further processing.

**3. Create `file.service.ts`:**

```typescript
// 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 `uploadFile` method, 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 `diskStorage` from 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:**

1. Install NestJS and necessary dependencies (refer to your project's requirements).
2. Create the `file.module.ts`, `file.controller.ts`, and `file.service.ts` files with the provided code (adapted to your project).
3. Run your NestJS application.
4. Use tools like Postman or curl to test the API:
   - **Endpoint:** `POST http://localhost:3000/file/upload`
   - **Body:** Use `form-data` and include a file with the field name `file`.
   - **Expected Response:** Details about the uploaded file or the result of additional actions.

## Testing the API using Postman:

 **Install Postman:**

   If you don't have Postman installed, download and install it from [Postman's official website](https://www.postman.com/).

 **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 `Body` tab.
   - Choose `form-data` as the body type.
   - Add a key-value pair with the key `file` and 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.