Web

ContentType 을 알아보자! (multipart/form-data, application/json)

hoonylab 2025. 4. 14. 16:40
728x90
반응형

📦 multipart/form-data vs application/json 비교

항목 multipart/form-data application/json
주 용도 파일 업로드 (이미지, 문서 등)와 일반 폼 데이터 전송 JSON 형식의 구조화된 데이터 전송
데이터 포맷 각 필드가 boundary로 구분되어 전송됨 전체 요청 본문이 JSON 문자열로 구성됨
파일 전송 가능 여부 ✅ 가능 ❌ 불가능
사용되는 HTTP 메서드 POST POST, PUT, PATCH
서버 파싱 방법 multipart 전용 파서 필요 (예: Multer, Formidable 등) 프레임워크에서 기본 지원
Content-Type 헤더 multipart/form-data; boundary=... application/json
프론트 전송 방식 FormData API 사용 JSON.stringify() 사용
장점 파일과 텍스트를 동시에 전송 가능 구조화된 데이터 전송에 적합
단점 파싱 복잡, 디버깅 어려움 파일 전송 불가능

✅ application/json 예제

프론트엔드 (Axios)


import axios from 'axios';

const data = {
  username: 'john_doe',
  age: 30,
};

axios.post('/api/json', data, {
  headers: {
    'Content-Type': 'application/json',
  },
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

백엔드 (Spring Controller)


@RestController
public class JsonController {

    @PostMapping("/api/json")
    public ResponseEntity<String> receiveJson(@RequestBody UserDto userDto) {
        return ResponseEntity.ok("Received JSON: " + userDto.getUsername());
    }

    public static class UserDto {
        private String username;
        private int age;

        // Getters and setters
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public int getAge() { return age; }
        public void setAge(int age) { this.age = age; }
    }
}

📂 multipart/form-data 예제

프론트엔드 (Axios + FormData)


import axios from 'axios';

const formData = new FormData();
formData.append('username', 'john_doe');
formData.append('profileImage', fileInput.files[0]); // fileInput은 input[type="file"]

axios.post('/api/form', formData, {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

백엔드 (Spring Controller)


@RestController
public class FormController {

    @PostMapping("/api/form")
    public ResponseEntity<String> receiveForm(
        @RequestParam("username") String username,
        @RequestParam("profileImage") MultipartFile file
    ) {
        String originalFileName = file.getOriginalFilename();
        return ResponseEntity.ok("Received file: " + originalFileName + ", username: " + username);
    }
}

✅ 마무리 정리

단순한 데이터 전송에는 application/json을, 파일과 데이터를 함께 보내야 하는 경우에는 multipart/form-data를 사용해야 합니다. 각 방식의 특성을 잘 이해하고 적절한 상황에 맞게 선택하는 것이 중요합니다.

728x90
반응형