Quangkhoi1228 | Knowledge base
  • Về trang chủ
  • Lời nói đầu
  • Nhập môn lập trình web
    • Giáo trình
    • Class 01: Hello HTML!!!
    • Class 02: HTML: Comment, Text formatting, Attribute, Link
    • Class 03: HTML: Style, Inline/Block element, Image
    • Class 04: HTML: List, Table, Responsive
    • Class 05: Hello CSS!!!
    • Class 06: CSS: Flexbox, Layout
    • Class 07: Hello Javascript!!!
    • Class 08: JS: Operator, Expression, For/While Loop, Function
    • Class 09: JS: Search Function
    • Project 1: Layout Structure
    • Project 2: Search Function
    • Project 3: MVP
    • Review "Lập trình Frontend Website"
  • Lập trình Frontend Website
    • Class 01: Ôn tập HTML
    • Class 02: Thảo luận HTML
    • Class 03: Ôn tập CSS
    • Class 04: Chrome dev tools, CSS Box Model
    • Class 05: CSS: Position, Đơn vị đo
    • Class 06: CSS: hiệu ứng, responsive
    • Class 07: Thảo luận CSS
    • Class 08: Ôn tập JS
    • Class 09: JS: Mảng, Đối tượng, Biến tham chiếu và tham trị
    • Class 10: JS: Class, Pair programming
    • Class 11: JS: DOM, UI Rendering
  • Lập trình ReactJS
    • Class 01: Giới thiệu ReactJS
    • Class 01: Tạo dự án ReactJS mới
    • Class 02: ReactJS Component
    • Class 02: Import/Export component
    • Class 03: useState hook
    • Class 04: Project 1: UI cơ bản
    • Class 05: Render có điều kiện và danh sách
    • Class 06: useEffect hook
    • Class 07: Project 2: Xử lý user logic
    • Class 08: Project 3: Hoàn thiện dashboard
    • Class 09: Form và dữ liệu người dùng
    • Class 10: UseRef và thao tác với DOM
    • Class 11: Project 4: Xử lý form data
    • Class 12: Project 5: Hoàn thiện form data
    • Class 13: useMemo và useCallback
    • Class 14: Custom Hook
    • Class 15: Project 6: Hoàn thiện project
    • Class 16: Ôn tập
  • Lập trình NestJS
    • Class 01: Giới thiệu NestJS & Cài đặt dự án
    • Class 02: Routing, Controller và Dependency Injection
    • Class 03: Service và Data Validation
    • Class 04: Kết nối Database với TypeORM
    • Class 05: Quan hệ trong Database (OneToMany, ManyToOne) với TypeORM
    • Class 06: Middleware, Interceptor, Guard
    • Class 07: Authentication – JWT
    • Class 08: Authorization – Phân quyền
    • Class 09: File Upload & Configuration
    • Class 10: Giới thiệu WebSocket
    • Class 11: Project 1
    • Class 12: Project 2
    • Class 13: Project 3
    • Class 14: Project 4
    • Class 15: Project 5
    • Class 16: Project 6
  • Lập trình Java cơ bản
    • Class 01: Khai giảng
    • Class 02: Hello Java
    • Class 03: Biến và kiểu dữ liệu
    • Class 04: Toán tử và biểu thức
    • Class 05: Câu lệnh điều kiện
    • Class 06: Review 1
    • Class 07: Vòng lặp For
    • Class 08: Vòng lặp While / Do-while
    • Class 09: Java Method
    • Class 10: Review 2
    • Class 11: Java User Input
    • Class 12: Java File
    • Class 13: Final Exam 1
    • Class 14: Final Exam 2
    • Review "Lập trình OOP với Java"
  • Lập trình OOP với Java
    • Class 01: Hello OOP
    • Class 02: Class Attribute và Method
    • Class 03: Constructor, Modifier và Package
    • Class 04: Review 1
    • Class 05: Tính kế thừa và đa hình
    • Class 06: Tính trừu tượng và đóng gói
    • Class 07: Review 2
    • Class 08: Final Exam 1
    • Class 09: Final Exam 2
    • Review "CTDL và Giải thuật với Java"
  • CTDL và Giải thuật với Java
    • Class 01: Hello Data Structure
  • HTML
    • Cài đặt công cụ cơ bản
    • HTML là gì?
    • Phần tử HTML
    • Cấu trúc file HTML cơ bản
    • Comment trong HTML
    • Format văn bản trong HTML
    • Thuộc tính HTML
    • Liên kết(link) trong HTML
    • Project: Professional Email
    • HTML Style
    • Phần tử Inline và Block
    • HTML Image
    • HTML List
    • HTML Table
    • Head trong HTML
    • HTML Responsive
    • Project: Online Cover Letter
  • CSS
    • Giới thiệu CSS
    • CSS Selector
    • Thêm CSS vào trang
    • Comment trong CSS
    • Màu sắc trong CSS
    • CSS Background
    • CSS Border
    • CSS Spacing
    • CSS Flexbox
    • HTML Layout
    • Chrome dev tools
    • CSS Box Model
    • CSS Position
    • Đơn vị đo trong CSS
    • CSS Pseudo-classes
    • CSS Responsive
  • JavaScript
    • Giới thiệu Javascript
    • Thêm JS vào trang
    • Các hàm có sẵn
    • Biến và kiểu dữ liệu
    • JS Mảng
    • JS Đối tượng
    • JS Biến Tham Chiếu và Tham Trị
    • Toán tử và biểu thức
    • Câu lệnh điều kiện
    • Vòng lặp For / While
    • Hàm (Function)
    • Chức năng tìm kiếm với JS và DOM
    • JS Class
    • JS DOM
    • JS Dom Rendering
  • Java
    • Giới thiệu Java
    • Chương trình Hello world
    • Phân biệt JVM, JRE, JDK
    • Java Comment
    • Biến trong Java
    • Kiểu dữ liệu trong Java
    • Java Array
    • Toán tử trong Java
    • Biễu thức trong Java
    • Java If-else
    • Java Switch
    • Vòng lặp For trong Java
    • Vòng lặp While trong Java
    • Vòng lặp Do-while trong Java
    • Java Method
    • Java OOP
    • Java Class và Object
    • Java Class attribute
    • Java Class method
    • Java Constructor
    • Java Modifier
    • Java Package
    • Java Tính kế thừa
    • Java Tính đa hình
    • Java Tính trừu tượng
    • Java Tính đóng gói
    • Java User Input
    • Java File
  • Soft skills
    • Pair Programming
  • Web design and wireframe
  • NextJS
    • Tạo dự án NextJS mới
  • NestJS
    • Giới thiệu NestJS
    • NestJS controller
    • NestJS module
  • Git
    • Setup SSH key với GitHub
  • Bash
    • Giới thiệu Bash/Shell Script
  • Wordpress
    • Thêm custom routes
    • Deploy with ubuntu
  • Deployment
    • SSH server, đổi password và add SSH key
    • Tạo user mới và add SSH key
    • Page
  • GitBook
    • Custom domain with CloudFlare
  • Hướng dẫn khác
    • Gitbook custom domain with Cloudflare
    • Cấu hình OpenVPN
    • Cấu hình và lấy SSH key
    • Công cụ lập trình
      • Visual Studio Code
      • Cài đặt IntelliJ IDEA
    • Đường dẫn file trong HTML
    • CI/CD github action
  • Project: CV online
Powered by GitBook
On this page
  • Cấu hình NestJS với @nestjs/config
  • Cài đặt
  • Tạo file .env ở thư mục gốc dự án
  • Cấu hình ConfigModule trong app.module.ts
  • Upload file với Multer (ảnh đại diện người dùng)
  • Cài đặt platform-express
  • Tạo controller xử lý upload ảnh đại diện
  • Xử lý lưu trữ file tạm trong thư mục static
  • Cài đặt ServeStaticModule
  • Cấu hình ServeStaticModule trong app.module.ts
  • Giải thích chi tiết
  • Bài tập thực hành cho học viên
  1. Lập trình NestJS

Class 09: File Upload & Configuration

Cấu hình NestJS với @nestjs/config

@nestjs/config giúp quản lý biến môi trường (environment variables) và cấu hình dự án một cách linh hoạt.

Cài đặt

npm install @nestjs/config

Tạo file .env ở thư mục gốc dự án

PORT=3000
UPLOAD_DIR=./public/uploads

Cấu hình ConfigModule trong app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,  // cho phép sử dụng config ở toàn bộ module
    }),
  ],
})
export class AppModule {}

Upload file với Multer (ảnh đại diện người dùng)

NestJS tích hợp Multer để xử lý upload file multipart/form-data rất tiện lợi qua FileInterceptor.

Cài đặt platform-express

npm install @nestjs/platform-express

Tạo controller xử lý upload ảnh đại diện

import { Controller, Post, UploadedFile, UseInterceptors, BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { ConfigService } from '@nestjs/config';

@Controller('users')
export class UsersController {
  constructor(private configService: ConfigService) {}

  @Post('upload-avatar')
  @UseInterceptors(
    FileInterceptor('avatar', {
      storage: diskStorage({
        destination: (req, file, cb) => {
          // Lấy thư mục upload từ biến môi trường, default './public/uploads'
          const uploadPath = this.configService.get<string>('UPLOAD_DIR') || './public/uploads';
          cb(null, uploadPath);
        },
        filename: (req, file, cb) => {
          // Đặt tên file upload dạng avatar-<timestamp>-<random>.<ext>
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = extname(file.originalname);
          cb(null, `avatar-${uniqueSuffix}${ext}`);
        },
      }),
      fileFilter: (req, file, cb) => {
        // Chỉ chấp nhận ảnh jpg, jpeg, png
        if (!file.mimetype.match(/\/(jpg|jpeg|png)$/)) {
          return cb(new BadRequestException('Chỉ chấp nhận file ảnh có định dạng jpg, jpeg, png!'), false);
        }
        cb(null, true);
      },
      limits: { fileSize: 2 * 1024 * 1024 }, // giới hạn kích thước 2MB
    }),
  )
  uploadAvatar(@UploadedFile() file: Express.Multer.File) {
    if (!file) {
      throw new BadRequestException('Không có file được gửi lên!');
    }
    const host = `http://localhost:${process.env.PORT || 3000}`;
    const imageUrl = `${host}/uploads/${file.filename}`;
    return {
      message: 'Upload ảnh đại diện thành công',
      filename: file.filename,
      url: imageUrl,
    };
  }
}

Xử lý lưu trữ file tạm trong thư mục static

Để truy cập được file upload từ trình duyệt, ta cần cấu hình serve thư mục public làm static.

Cài đặt ServeStaticModule

npm install @nestjs/serve-static

Cấu hình ServeStaticModule trong app.module.ts

import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'public'), // thư mục public nằm ngoài src
      serveRoot: '/uploads', // truy cập file qua http://localhost:3000/uploads/filename
    }),
    // Các module khác
  ],
})
export class AppModule {}

Giải thích chi tiết

  • @nestjs/config: Đọc biến môi trường, tránh hardcode cấu hình, dễ thay đổi môi trường khác nhau.

  • FileInterceptor: Middleware xử lý file upload, nhận key form data avatar.

  • diskStorage: Thiết lập thư mục lưu và tên file lưu.

  • fileFilter: Lọc file theo định dạng, đảm bảo chỉ ảnh hợp lệ được upload.

  • limits: Giới hạn kích thước file upload.

  • ServeStaticModule: Cho phép truy cập file upload qua URL, phục vụ file tĩnh.


Bài tập thực hành cho học viên

  • Tạo file .env với UPLOAD_DIR=./public/uploads.

  • Cài đặt và cấu hình @nestjs/config theo hướng dẫn.

  • Tạo controller với route POST /users/upload-avatar để upload file ảnh đại diện.

  • Giới hạn file upload chỉ nhận jpg, jpeg, png, kích thước tối đa 2MB.

  • Lưu file vào thư mục public/uploads theo cấu hình.

  • Cấu hình serve static thư mục public để truy cập file upload qua URL.

  • Sử dụng Postman hoặc frontend test upload file.

  • Kiểm tra upload thành công, trả về URL file, truy cập URL ảnh trên trình duyệt.

  • Thử upload file không phải ảnh hoặc quá lớn để kiểm tra lỗi.

PreviousClass 08: Authorization – Phân quyềnNextClass 10: Giới thiệu WebSocket

Last updated 3 days ago