두리공장
[Spring & jQuery] 파일 및 Json 데이터 업로드 (file & json data) 본문
파일 업로드를 하려고 한다. 그런데, 파일만 올려야되는 것은 아니고, json data도 동시에 업로드 해야 한다면?
먼저, html 부터 작성해 본다.
<form action="upload" id="uploadForm" method="post" enctype="multipart/form-data">
<input type="file" name="file1" id="file1" style="display:none" accept=".gif, .jpg, .jpeg, .png" />
<button type="button" class="fileUploadBtn" id="add_file1"><span class="blind">사진추가</span></button>
</form>
.
.
.
<script type="text/javascript">
$(document).ready(function(){
/* 파일첨부버튼 클릭시 */
$("#add_file1").bind("click", function (){
$("#file1").click();
});
/*파일이 변경된 경우*/
$("#file1").on("change", function(e){
handleImgFileSelect(e, function(result){
if(result){
fn_submit();
}
else{
alert("확장자는 이미지 확장자만 가능합니다");
return;
}
});
});
//이미지 여부 확인
function handleImgFileSelect(e, callback) {
console.log("e:",e);
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var reg = /(.*?)\/(jpg|jpeg|png|bmp)$/;
var result = true;
for(var i =0; i < filesArr.length; i++){
if(!filesArr[i].type.match(reg)){
result = false;
}else{
if(result) {
result = true;
}else{
result = false;
}
}
}
callback(result);
}
//파일 업로드
function fn_submit(){
var jsondata = {"custno": "110111", "gubunname": "자동차등록증"};
var form = $("#form")[0];
var formData = new FormData();
formData.append("file", $("#file1")[0].files[0]);
formData.append("jsondata", new Blob([JSON.stringify(jsondata)], {type: "application/json"}));
$.ajax({
url: "http://localhost:8080/file/upload",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function(res){
alert("파일 업로드를 성공하였습니다");
console.log("res:", res);
},
error: function(err){
alert(err.responseText);
}
});
}
</script>
"사진추가" 버튼(add_file1)에 클릭 이벤트를 건다. 버튼을 클릭하면 파일 업로드 다이얼로그 창이 뜬다.(accept 에 확장자를 등록하면 다이얼로그 창에 필터 기능이 적용된다)
파일업로드시 이미지 확장자만 첨부가 가능하도록 handleImgFileSelect 함수를 이벤트 발생시 호출해 준다. 파일명이 이미지인 경우에만 서버에 업로드 할 수 있다.
formData에 두가지 데이터 타입을 동시에 업로드 해야 하므로, formData.append에 file과 jsondata를 추가하되, jsondata에는 contentType 을 application/json으로 명시해 두어야 한다.
이제, 서버측 코드를 작성해 보자.
@RequestMapping(value = "/file")
@RestController
public class FileController {
private String path = System.getProperty("user.dir");
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public FileVO upload(@RequestPart(value = "file", required = false)MultipartFile multi,
@RequestPart(value = "jsondata") FileVO fileVO) {
try{
String uploadPath = path + "/upload";
String originalFilename = multi.getOriginalFilename();
String ext = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
long size = multi.getSize();
String saveFilename = originalFilename;
if(!multi.isEmpty()){
File file = new File(uploadPath, multi.getOriginalFilename());
multi.transferTo(file);
fileVO.setResultcode("0");
fileVO.setErrorMsg("");
}
}catch (Exception e){
System.out.println(e.getMessage());
fileVO.setErrorMsg(e.getMessage());
fileVO.setResultcode("1");
}
return fileVO;
}
}
프로젝트의 디렉토리 위치를 찾기 위해서 System.getProperty("user.dir");을 사용하였다.
file 과 Jsondata 를 동시에 받기 위해서 @RequestPart 를 사용하였다. JsonData는 VO에 미리 선언해 준다.
@Data
public class FileVO {
private String custno;
private String gubunname;
private String gubuncode;
private String resultcode;
private String errorMsg;
}
이렇게 하고나서 서버에서 파일을 업로드 하면, 정상적으로 응답이 온다..
{"custno":"110111","gubunname":"자동차등록증","gubuncode":null,"resultcode":"0","errorMsg":""}
끝.
'java' 카테고리의 다른 글
[Spring batch] Step 9 - 배치시작을 위한 config 및 h2 메모리DB구성, 그리고 itemprocessor 사용 (0) | 2022.06.11 |
---|---|
spring job scheduler & shedLock 적용 (0) | 2022.06.09 |
[Spring batch] Step 8 - 2개이상 write 작업수행을 위해 CompositeItemWriter를 사용하자 (데이터 출력을 위한 CustomItemWriter 작성 포함) (0) | 2022.05.26 |
[Spring batch] Step 7 - Multi DataSource 사용하기 (0) | 2022.05.24 |
[Spring batch] Step 6 - DB를 읽어서 서비스 Method 호출하기 (0) | 2022.05.22 |