자바스크립트로 작성된 NestJS 웹 애플리케이션의 파일 다운로드 기능 구현

NestJS는 Node.js 서버 사이드 프레임워크로, 자바스크립트로 서버 애플리케이션 개발을 손쉽게 할 수 있는 도구입니다. 이번 글에서는 NestJS를 사용하여 파일 다운로드 기능을 구현하는 방법에 대해 알아보겠습니다.

1. 파일 다운로드를 위한 API 엔드포인트 생성

먼저, 파일 다운로드를 위한 API 엔드포인트를 생성해야 합니다. NestJS에서는 @Get() 데코레이터를 사용하여 GET 요청을 처리하는 메서드를 작성할 수 있습니다.

import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';

@Controller('files')
export class FilesController {
  @Get()
  async downloadFile(@Res() res: Response) {
    // 파일 다운로드 로직 작성
  }
}

위 코드에서 downloadFile 메서드는 @Res() 데코레이터를 사용하여 express 응답 객체를 주입받습니다.

2. 파일 다운로드 로직 작성

다음으로, 파일 다운로드 로직을 작성해야 합니다. 파일을 다운로드하기 위해서는 express 응답 객체의 download() 메서드를 사용하면 됩니다. 이 메서드에는 다운로드할 파일의 경로와 파일명을 인자로 전달합니다.

import { Injectable } from '@nestjs/common';
import { Response } from 'express';

@Injectable()
export class FilesService {
  async downloadFile(res: Response) {
    const filePath = '/path/to/file.pdf';
    const fileName = 'file.pdf';

    res.download(filePath, fileName);
  }
}

위 코드에서는 downloadFile 메서드를 FilesService에 작성하고, 해당 메서드 내에서 파일 경로와 파일명을 설정하여 res.download() 메서드를 호출합니다.

3. API 엔드포인트와 서비스 연결

마지막으로, 생성한 FilesControllerFilesService를 연결해주어야 합니다. NestJS에서는 @Injectable() 데코레이터를 사용하여 서비스를 주입받을 수 있습니다.

import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
import { FilesService } from './files.service';

@Controller('files')
export class FilesController {
  constructor(private readonly filesService: FilesService) {}

  @Get()
  async downloadFile(@Res() res: Response) {
    await this.filesService.downloadFile(res);
  }
}

위 코드에서 FilesController의 생성자에서 FilesService를 주입받아 사용할 수 있습니다. downloadFile 메서드에서는 FilesServicedownloadFile 메서드를 호출하여 파일 다운로드 로직을 처리합니다.

4. 웹 애플리케이션에서 파일 다운로드 요청하기

이제, 생성한 파일 다운로드 API를 웹 애플리케이션에서 사용할 수 있습니다. 예를 들어, HTML에서 버튼을 클릭할 때 파일 다운로드를 요청하도록 구현해보겠습니다.

<button onclick="downloadFile()">파일 다운로드</button>

<script>
  async function downloadFile() {
    const response = await fetch('/files');
    const blob = await response.blob();

    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'file.pdf';
    link.click();
  }
</script>

위 코드에서는 클라이언트 측에서 fetch() 함수를 사용하여 서버로 파일 다운로드 요청을 보내고, 받은 응답 데이터를 Blob으로 변환합니다. 그리고 변환한 Blob 객체를 사용하여 <a> 요소를 동적으로 생성하고, href 속성과 download 속성을 설정하여 파일을 다운로드할 수 있게 합니다.

이제 NestJS 애플리케이션에서 파일 다운로드 기능을 구현하기 위한 모든 단계를 마쳤습니다. 상세한 내용과 더 많은 기능에 대해서는 NestJS 공식 문서를 참고하시기 바랍니다.

#nestjs #javascript