[DEV] 기록

[SpringBoot] ajax를 통해 파일과 json 컨트롤러로 보내는 방법

꾸준함. 2022. 3. 15. 15:50

개요

ajax를 통해 파일과 json을 동시에 보내야 하는 상황이 생겨 방법을 정리해봤습니다.

 

코드

 

1. view


<form id="uploadForm" name="uploadForm" method="post" enctype="multipart/form-data">
<table class="edit-table">
<tr>
<th>파일</th>
<td>
<input id="file" type="file" name="file">
</td>
</tr>
<tr>
<th>ID</th>
<td>
<input type="text" id="id" name="id"/>
</td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="text" id="password" name="password" />
</td>
</tr>
</table>
</form>
<script type="text/javascript">
$('#edit-table').submit(function(event) {
var file = $('#file')[0].files[0];
var formData = new FormData();
formData.append('file', file);
var data = {
id: $('#id').val(),
password: $('#password').val()
};
formData.append("account", new Blob([JSON.stringify(data)], {type: "application/json"}));
$.ajax({
url: "/sample/api",
method: "post",
data: formData,
contentType: false,
processData: false,
cache: false,
enctype: 'multipart/form-data',
dataType: "json",
success: function(result) {
// 성공 시 처리
},
error: function (xhr, status, error) {
// 실패 시 처리
}
});
});
</script>
view raw .html hosted with ❤ by GitHub

 

2. Controller

 

@PostMapping(value = "/sample/api"
, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public ModelAndView sampleApi(
HttpServletRequest request,
@RequestPart("file") MultipartFile file,
@RequestPart("account") Account account) throws IOException {
// 비즈니스 로직
ModelAndView mav = new ModelAndView("jsonView");
mav.addObject("code", 1);
mav.addObject("msg", "정상적으로 처리되었습니다.");
return mav;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Account {
private String id;
private String password;
}
view raw .java hosted with ❤ by GitHub

 

* 이처럼 @RequestPart 어노테이션을 통해 파일과 json을 각각 따로 받으면 ajax로 한 번에 파일과 json을 보낼 수 있습니다.

 

반응형