[typescript] 타입스크립트에서 Axios를 이용한 파일 업로드

이번 포스트에서는 타입스크립트에서 Axios를 사용하여 파일을 서버에 업로드하는 방법에 대해 알아보겠습니다.

Axios 설치

먼저 npm을 사용하여 Axios를 설치합니다.

npm install axios

또한, @types/axios를 설치하여 타입스크립트에서 Axios를 사용하기 위한 타입 정의를 추가합니다.

npm install @types/axios

파일 업로드 예제

아래는 타입스크립트에서 Axios를 사용하여 파일을 업로드하는 간단한 예제입니다.

import axios from 'axios';

const uploadFile = async (file: File) => {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log('File uploaded successfully:', response.data);
  } catch (error) {
    console.error('Error uploading file:', error);
  }
};

이 예제에서는 FormData를 사용하여 파일을 포함한 데이터를 생성하고, axios.post 메서드를 호출하여 서버에 파일을 업로드합니다. 또한, Content-Type 헤더를 multipart/form-data로 설정하여 파일 업로드를 지원합니다.

마무리

이렇게 타입스크립트에서 Axios를 사용하여 간단히 파일을 업로드하는 방법에 대해 알아보았습니다. Axios를 이용하면 간편하게 파일 업로드를 처리할 수 있으며, 타입스크립트에서도 타입 안정성을 유지할 수 있습니다.

내용이 도움이 되었기를 바라며, 더 궁금한 점이 있으면 문의해주세요!