파일 업로드
파일 2개 받아보기
@Post('/uploads/multi')
@UseInterceptors(
FileFieldsInterceptor([
{ name: 'file1', maxCount: 1 },
{ name: 'file2', maxCount: 1 },
]),
)
uploadMultiFile(
@UploadedFiles() files: { file1: Express.Multer.File; file2: Express.Multer.File },
) {
console.log(files.file1[0], files.file2[0])
}
받을 파일을 서버에 저장하기
@Post('/uploads/multi')
@UseInterceptors(
FileFieldsInterceptor([
{ name: 'file1', maxCount: 1 },
{ name: 'file2', maxCount: 1 },
]),
)
uploadMultiFile(
@UploadedFiles() files: { file1: Express.Multer.File; file2: Express.Multer.File },
) {
return this.boardService.fileUpload(files.file1[0], files.file2[0]);
}
fileUpload(file1: Express.Multer.File, file2: Express.Multer.File) {
if (!file1 || !file2) {
throw new BadRequestException('파일이 존재하지 않습니다.');
}
// 파일 처리 로직
return { file1Path: file1.path, file2Path: file2.path };
}
import { Injectable } from '@nestjs/common';
import { MulterOptionsFactory } from '@nestjs/platform-express';
import * as path from 'path';
import * as fs from 'fs';
import * as multer from 'multer';
@Injectable()
export class MulterConfigService implements MulterOptionsFactory {
dirPath: string;
constructor() {
this.dirPath = path.join(__dirname, '..', '..', '..', 'public', 'uploads');
this.mkdir();
}
mkdir() {
try {
fs.readdirSync(this.dirPath);
} catch (error) {
fs.mkdirSync(this.dirPath);
}
}
createMulterOptions() {
const dirPath = this.dirPath;
const options = {
storage: multer.diskStorage({
// 파일 저장위치 설정
destination(req, file, done) {
done(null, dirPath);
},
// 파일명 설정
filename(req, file, done) {
const ext = path.extname(file.originalname);
const fileName = path.basename(file.originalname, ext) + new Date().valueOf() + ext;
done(null, fileName);
},
}),
// limit: { fileSize: 5 * 1024 * 1024 }, // 용량 제한
};
return options;
}
}
import { Module } from '@nestjs/common';
import { BoardService } from './board.service';
import { BoardController } from './board.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Board } from './entities/board.entity';
import { MulterModule } from '@nestjs/platform-express';
import { MulterConfigService } from '../../util/upload/multer.config';
@Module({
imports: [
TypeOrmModule.forFeature([Board]),
MulterModule.registerAsync({
useClass: MulterConfigService,
}),
],
controllers: [BoardController],
providers: [BoardService],
})
export class BoardModule {}
저장된 파일 다운로드 받아보기
@Get('download/:filename')
downloadFile(@Param('filename') filename: string, @Res() res: Response) {
const filePath = path.join(__dirname, '..', '..', '..', 'public', 'uploads', filename);
// 파일 존재 여부 확인
if (!fs.existsSync(filePath)) {
throw new NotFoundException('파일을 찾을 수 없습니다.');
}
// 응답 헤더 설정
res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
// 파일 스트림 생성 및 응답으로 보내기
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
}