[javascript] Axios를 이용한 파일 업로드

Axios는 HTTP 요청을 보내고 받기 위해 사용되는 JavaScript 라이브러리입니다. 파일 업로드는 웹 애플리케이션에서 자주 사용되는 기능이며, Axios를 사용하면 간편하게 파일을 업로드할 수 있습니다.

파일 선택하기

먼저 파일 업로드를 위해 사용자가 파일을 선택할 수 있는 input 요소를 생성해야 합니다. HTML에서는 <input type="file">을 사용하여 파일 선택 창을 생성할 수 있습니다.

<input type="file" id="fileInput">
<button onclick="uploadFile()">파일 업로드</button>

파일 업로드하기

Axios를 사용하여 파일을 업로드하는 함수를 작성해보겠습니다.

function uploadFile() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];

  const formData = new FormData();
  formData.append('file', file);

  axios.post('/upload', formData)
    .then(response => {
      console.log(response.data);
    })
    .catch(error => {
      console.error(error);
    });
}

위 코드에서는 먼저 파일 선택 창에서 선택된 파일을 가져온 후 FormData를 사용하여 파일을 담고 있습니다. 그리고 axios.post를 호출하여 서버로 파일을 전송합니다. 업로드에 성공하면 응답 데이터를 콘솔에 출력하고, 실패하면 에러를 콘솔에 출력합니다.

서버 측 코드

파일 업로드를 처리하기 위해서는 서버 측에서도 처리할 수 있는 코드가 필요합니다. 여기서는 Node.js와 Express를 사용하는 예제를 보여드리겠습니다.

const express = require('express');
const multer = require('multer');

const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
  res.json({ message: '파일 업로드 성공' });
});

app.listen(3000, () => {
  console.log('서버가 시작되었습니다.');
});

위 예제에서는 multer를 사용하여 파일 업로드를 처리합니다. upload.single('file')을 사용하면 file 필드 이름으로 전송된 파일을 받아올 수 있습니다. 업로드에 성공한 경우에는 JSON 응답이 반환됩니다.

결론

Axios를 이용하여 파일 업로드를 구현하는 방법에 대해 알아보았습니다. Axios의 간편한 인터페이스를 통해 파일 업로드를 쉽게 처리할 수 있으며, 서버 측에서는 multer 등의 라이브러리를 사용하여 파일 업로드를 처리할 수 있습니다.