728x90
FormData
HTML의 form 태그 내의 form 필드(키)와 그 값을 나타내는 키-값 쌍을 쉽게 생성할 수 있게 해주는 객체이다.
텍스트데이터, 파일을 서버로 전송하게 해준다.
1개의 파일과 텍스트데이터를 서버로 전송할 때
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script>
//FormData 객체 생성, 파일을 포함한 데이터 전송 가능하게 해주는 객체이다.
let formData = new FormData();
//사용자가 선택한 파일
let fileField = document.querySelector('input[type="file"]');
//텍스트 데이터
formData.append('username', 'abc123')
//파일
formData.append('attachment', fileFied.files[0]);
fetch('url', {
method : 'POST',
body : formData
})
.then(response => response.json())
.catch(error => console.error('Error : ', error))
.then(response => console.log('Success : ', JSON.stringify(response)));
</script>
</body>
</html>
2개 이상의 다중 파일을 서버로 전송할 때
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script>
//FormData 객체 생성, 파일을 포함한 데이터 전송 가능하게 해주는 객체이다.
let formData = new FormData();
//사용자가 선택한 파일, 다중 파일 선택 HTML 요소
let fileField = document.querySelector('input[type="file"][multiple]');
//텍스트 데이터
formData.append('username', 'abc123')
//파일
for (let i = 0; i < fileField.files.length; i++) {
formData.append('attachment', fileFied.files[i]);
}
fetch('url', {
method : 'POST',
body : formData
})
.then(response => response.json())
.then(response => console.log('Success : ', JSON.stringify(response)))
.catch(error => console.error('Error : ', error));
</script>
</body>
</html>
참고자료
'자바스크립트' 카테고리의 다른 글
Javascript, cookie에서 csrftoken 값 가져오기 (0) | 2022.07.27 |
---|---|
frontend, pipe에러 해결 (0) | 2022.07.25 |
Javascript, fetch PUT (0) | 2022.07.21 |
Javascript, fetch POST (0) | 2022.07.21 |
Javascript, fetch GET (0) | 2022.07.21 |