JavaScript - 파일 업로드 구현하기 multipart/form-data

반응형

파일 업로드 구현할 때,

input file 태그에서 파일을 입력받고 파일 업로드를 하고

FormData에 파일을 넣고 axios post 메서드를 이용해서 파일 전송을 할 수 있습니다.

파일 업로드 예시

<input type="file" id="fileInput">
<button id="uploadBtn">파일 업로드</button>
const uploadBtn = document.getElementById('uploadBtn');

uploadBtn.addEventListener('click', () => {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files;
  const formData = new FormData();
  forData.append('file', file);

  cosnt response = axios.post('/upload', formData, {
   headers: {
      'Content-Type': 'multipart/form-data',
   }
  }
});

 

FormData 란

HTML5에서 form 태그를 이용해서 key & value 값을 쉽게 생성할 수 있습니다.

<form action="/submit" method="post" enctype="multipart/form-data">
   <label for="username">사용자 이름:</label>
   <input type="text" id="username" name="username" required>
   <label for="password">비밀번호:</label>
   <input type="password" id="password" name="password" required>
   <label for="file">파일 업로드:</label>
   <input type="file" id="file" name="file" accept=".jpg, .jpeg, .png" required>
   <button type="submit">제출</button>
</form>

 

자바스크립트에서는 FormData를 이용해서 key & value 값을 생성할 수 있습니다.

 

FormData 객체에 파일을 담고

헤더에 Content-Type을통해서 multipary/form-data 설정하여

파일을 전송할 수 있습니다.

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

Content-Type: multipart/form-data

대부분의 전송에서의 기본값은 application/x-www-form-urlencoded 방식으로 전달됩니다.

간단한 텍스트등 전달은 가능하지만, 파일, 이진 데이터 등을 전송할 때는 multipart/form-data 타입을 사용해야 합니다.

 

multipart/form-data는 문자를 인코딩 되지 않고 전달하게 됩니다.

주로 이미지나 파일을 서버에 전달할 때 사용되는 방식입니다.

728x90
반응형