Skip to Content
BackendNestJs24-file-upload-classic

1. Multer 세팅

Multer를 사용해 파일 업로드를 구현할 것이다.

shellscript
1
yarn add multer @types/multer uuid @types/uuid

posts 엔티티에 이미지 프로퍼티를 추가한다.

posts.entity.ts
1
// 생략
2
3
@Entity()
4
export class PostsModel extends BaseModel {
5
// 생략
6
7
@Column({
8
nullable: true,
9
})
10
image?: string
11
12
// 생략
13
}

common/const/path.const.ts 파일을 만든다.

common/const/path.const.ts
1
import { join } from 'path'
2
import * as process from 'process'
3
4
// 서버 프로젝트의 루트 폴더
5
export const PROJECT_ROOT_PATH = process.cwd()
6
// 외부에서 접근 가능한 파일들을 모아둔 폴더 이름
7
export const PUBLIC_FOLDER_NAME = 'public'
8
// 포스트 이미지들을 저장할 폴더 이름
9
export const POSTS_FOLDER_NAME = 'posts'
10
11
// 실제 공개폴더의 절대 경로
12
// /{프로젝트의 위치}/public
13
export const PUBLIC_FOLDER_PATH = join(PROJECT_ROOT_PATH, PUBLIC_FOLDER_NAME)
14
15
// 포스트 이미지를 저장할 폴더
16
// /{프로젝트의 위치}/public/posts
17
export const POST_IMAGE_PATH = join(PUBLIC_FOLDER_PATH, POSTS_FOLDER_NAME)
18
19
// 절대경로 x
20
// public/posts/xxx.jpg
21
export const POST_PUBLIC_IMAGE_PATH = join(PUBLIC_FOLDER_NAME, POSTS_FOLDER_NAME)
  • 추가적으로 프로젝트의 루트 경로에 public/posts 폴더를 만든다.

posts 모듈에서 Multer 모듈을 전부 import한다.

posts.module.ts
1
import * as multer from 'multer'
2
import { v4 as uuid } from 'uuid'
3
// 생략
4
5
@Module({
6
imports: [
7
/*** 모델에 해당하는 repostory를 주입 ==> forFeature
8
* repository : 해당 모델을 다룰 수 있게 해주는 클래스
9
*/
10
TypeOrmModule.forFeature([
11
PostsModel, //
12
]),
13
AuthModule,
14
UsersModule,
15
CommonModule,
16
MulterModule.register({
17
limits: {
18
// byte 단위로 입력 (10000000byte -> 10MB가 넘는 파일은 에러)
19
fieldSize: 10000000,
20
},
21
/*** cb(에러, boolean)
22
* 첫번쨰 파라미터에는 에러가 있을 경우 에러 정보를 넣어준다.
23
* 두번쨰 파라미터는 파일을 받을지 말지 boolean을 넣어준다.
24
*/
25
fileFilter: (req, file, cb) => {
26
// xxx.jpg -> .jpg같이 확장자만 가져와줌
27
const ext = extname(file.originalname)
28
29
if (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png') {
30
return cb(
31
new BadRequestException('jpg/jpeg/png 파일만 업로드 가능합니다!'), //
32
false,
33
)
34
}
35
return cb(null, true)
36
},
37
storage: multer.diskStorage({
38
// 파일을 어디에 보낼지
39
destination: function (req, res, cb) {
40
cb(null, POST_IMAGE_PATH)
41
},
42
filename: function (req, file, cb) {
43
cb(null, `${uuid()}${extname(file.originalname)}`)
44
},
45
}),
46
}),
47
],
48
// 생략
49
})
50
export class PostsModule {}

2. FileInterceptor 적용

posts 컨트롤러에 이미지를 받을 파라미터를 받아서 넘겨준다.

posts.controller.ts
1
// posts.controller.ts 생략
2
@Post()
3
@UseGuards(AccessTokenGuard)
4
@UseInterceptors(FileInterceptor('image'))
5
postPosts(
6
@User('id') userId: number,
7
@Body() body: CreatePostDto,
8
@UploadedFile() file?: Express.Multer.File,
9
// @Body('title') title: string,
10
// @Body('content') content: string,
11
// 기본값을 true로 설정하는 파이프
12
// @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
13
) {
14
return this.postsService.createPost(userId, body, file?.filename)
15
}

posts 서비스에서 받은 이미지를 저장한다.

posts.service.ts
1
// posts.service.ts 생략
2
async createPost(authorId: number, postDto: CreatePostDto, image?: string) {
3
const post = this.postsRepository.create({
4
author: {
5
id: authorId,
6
},
7
...postDto,
8
image,
9
likeCount: 0,
10
commentCount: 0,
11
})
12
const newPost = await this.postsRepository.save(post)
13
return newPost
14
}