NestJS 서버에 있는 파일을 클라이언트로 전달하기 - 4

 

이제 서버에 있는 파일을 클라이언트가 다운받을수 있도록 API를 만들도록 하겠습니다.


이전글 : NestJS AWS S3버킷에 저장되어있는 파일을 서버에 저장하기 - 3: S3 Bucket의 파일을 다운로드 하기


import {
Controller,
Get,
Query,
Response,
StreamableFile,
} from '@nestjs/common';
import { ApiQuery, ApiTags } from '@nestjs/swagger';
import { createReadStream } from 'fs';
import { join } from 'path';

@ApiTags('서버로부터 다운로드 받기')
@Controller('download-file')
export class DownloadFileController {
@Get()
@ApiQuery({
name: 'fn',
description: '다운로드 받을 파일이름을 입력한다.(존재해야함)',
required: true,
type: String,
example: 'test.txt',
})
async download(
@Query('fn') fileName: string,
@Response({ passthrough: true }) res,
): Promise<StreamableFile> {
// 프로젝트 폴더 경로를 나타내 준다
console.log('process.cwd() : ', process.cwd());

// stream file을 생성해 준다.
const file = createReadStream(join(process.cwd(), `uploads/${fileName}`));

// // 아래는 res.set을 이용하여 Content-Type, Content-Disposition를 다른걸로 변경이 가능합니다.
// // Content-Type의 Default는 application/octet-stream
// res.set({
// 'Content-Type': 'application/json',
// 'Content-Disposition': 'attachment; filename="package.json"',
// });

// 입력한 fileName으로 전달할 파일 이름을 설정합니다.
res.set({
'Content-Disposition': `attachment; filename="${fileName}"`,
});
// stream file을 client쪽으로 전달한다.
return new StreamableFile(file);
}
}

코드1) Controller 코드


위 코드는 공식 문서를 참고해서 작성한 코드입니다. 해당 링크를 참고해 주시기 바랍니다.


사진1) uploads폴더안에 test.txt파일을 생성해 줍니다.


사진2) Swagger 프런트


사진3) 다운결과


해당 파일에 대해서 요청을 하게 되면 사진3에서 'Download file'링크를 주게 되어있습니다. 이것을 클릭하게 되면 클라이언트의 로컬 PC에 파일을 다운로드 할수 있습니다.


GitHub Branch(master)




댓글

이 블로그의 인기 게시물

Lesson 12_1 프로퍼티 노드(Property Node)

DAQ로 전압 측정하기-2

Nest JS URL에 있는 쿼리(Query) 읽기