개요
ajax를 통해 파일과 json을 동시에 보내야 하는 상황이 생겨 방법을 정리해봤습니다.
코드
1. view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
2. Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} |
* 이처럼 @RequestPart 어노테이션을 통해 파일과 json을 각각 따로 받으면 ajax로 한 번에 파일과 json을 보낼 수 있습니다.
반응형
'[DEV] 기록' 카테고리의 다른 글
[javascript] JSZip을 활용하여 form에 올라간 zip 파일 내 json 파일 읽기 (0) | 2022.03.16 |
---|---|
[SpringBoot] RestTemplate을 통해 MultipartFile 보내는 방법 (0) | 2022.03.15 |
[SpringBoot] 대용량 엑셀 파일 생성 및 다운로드 삽질기 (6) | 2022.03.13 |
[javascript] Invalid shorthand property initializer (0) | 2022.03.04 |
[구글 드라이브] 뷰어가 다운로드할 수 없는 PDF 다운로드 받는 방법 (50) | 2022.03.03 |