[typescript] Superagent를 이용한 파일 업로드 및 다운로드

Superagent는 Node.js 및 브라우저에서 사용할 수 있는 HTTP 클라이언트 라이브러리로, 편리하고 강력한 API를 제공합니다. 이 라이브러리를 활용하여 파일 업로드 및 다운로드 기능을 구현할 수 있습니다. 이번 포스트에서는 Superagent를 사용하여 파일 업로드와 다운로드를 구현하는 방법에 대해 알아보겠습니다.

필수 패키지 설치

먼저 Superagent를 설치하려면 다음 명령을 사용합니다.

npm install superagent

그리고, TypeScript를 사용한다면 TypeScript 타입 정의를 설치합니다.

npm install --save-dev @types/superagent

파일 업로드

Superagent를 사용하여 파일을 업로드하기 위해서는 send 메서드를 사용하여 파일을 전송할 수 있습니다. 아래의 예시는 TypeScript로 작성된 파일 업로드 코드입니다.

import * as superagent from 'superagent';

const uploadFile = async (filePath: string) => {
  try {
    const res = await superagent
      .post('https://example.com/upload')
      .attach('file', filePath)
      .field('name', 'example file');
    console.log(res.text);
  } catch (err) {
    console.error(err);
  }
};

uploadFile('path/to/file.jpg');

위 코드에서는 superagent.post 메서드를 사용하여 파일을 업로드하고 있습니다. attach 메서드를 사용하여 파일을 추가하고, field 메서드를 사용하여 추가 데이터를 전송할 수 있습니다.

파일 다운로드

Superagent를 사용하여 파일을 다운로드하는 경우에는 responseTypeblob으로 설정하여 바이너리 파일을 받을 수 있습니다. 아래의 예시는 TypeScript로 작성된 파일 다운로드 코드입니다.

import * as superagent from 'superagent';

const downloadFile = async (url: string, filePath: string) => {
  try {
    const res = await superagent.get(url).responseType('blob');
    const buffer = Buffer.from(res.body);
    // 파일로 저장 또는 처리
  } catch (err) {
    console.error(err);
  }
};

downloadFile('https://example.com/file.jpg', 'path/to/save/file.jpg');

위 코드에서는 superagent.get 메서드를 사용하여 파일을 다운로드하고 있습니다. responseTypeblob으로 설정하여 바이너리 파일을 받아올 수 있습니다. 받아온 파일은 원하는 처리를 한 뒤에 저장할 수 있습니다.

이상으로 Superagent를 사용하여 파일 업로드 및 다운로드 기능을 구현하는 방법에 대해 알아보았습니다. Superagent의 강력한 API를 활용하여 다양한 HTTP 요청을 처리할 수 있습니다.

참고 자료