FormData
는 웹 애플리케이션에서 폼 데이터를 쉽게 생성하고 제출할 수 있도록 도와주는 JavaScript 객체입니다. 이를 통해 폼 데이터를 AJAX를 사용하여 서버에 비동기적으로 전송할 수 있습니다. 또한, 파일 업로드와 같은 작업을 수월하게 처리할 수 있습니다.
FormData
객체를 생성하는 것은 매우 간단합니다.
const formData = new FormData();
append()
메서드를 사용하여 데이터를 FormData
객체에 추가할 수 있습니다.
formData.append('username', 'johndoe');
formData.append('email', 'johndoe@example.com');
FormData
는 파일도 다룰 수 있습니다. <input type="file">
요소에서 파일을 가져와 추가할 수 있습니다.
<input type="file" id="fileInput">
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
formData.append('profile_pic', file);
FormData
객체를 서버에 전송하려면, fetch()
나 XMLHttpRequest
와 같은 AJAX 기술을 사용할 수 있습니다.
fetch('YOUR_API_ENDPOINT', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Content-Type: FormData 요청은 일반적으로 multipart/form-data를 Content-Type으로 가지고 있습니다. 이 헤더를 확인하여 요청이 FormData를 사용하여 전송되었는지 확인할 수 있습니다.