Controller 작성
@RequestMapping(value = "/Download", method = RequestMethod.POST)
@ResponseBody
public String downloadOf(String fileName, HttpServletRequest request) throws JsonProcessingException {
Map<String, String> responseMap = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper();
try {
// 테스트 데이터 작성
List<String> testList = testService.test1(tDate);
// 파일 다운로드 처리
responseMap = testService.fileDownload(fileName, testList);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
responseMap.put("result", "ERROR");
}
return objectMapper.writeValueAsString(responseMap);
}
Service 작성
public Map<String, String> fileDownload(String fileName, List<String> testList) {
Map<String, String> responseMap = new HashMap<>();
String base64str;
String downloadFileName;
try {
// tsv 파일 생성
StringBuilder tsvContentBuilder = new StringBuilder();
for (String test : testList) {
String tsvLine = deleteBracketNChangeTab(test);
tsvContentBuilder.append(tsvLine).append(System.lineSeparator());
}
String tsvContent = tsvContentBuilder.toString();
// zip 파일 생성
String outputPath = String.format(webSecurityConfig.downloadFilename, fileName);
createZipFile(outputPath, fileName + ".tsv", tsvContent);
// zip 파일을 base64로 변환
base64str = convertFileToBase64(outputPath);
// 임시 ZIP 파일 삭제
File file = new File(outputPath);
if (file.exists()) {
file.delete();
}
responseMap.put("mimetype", "application/zip");
responseMap.put("filename", _route);
responseMap.put("result", "OK");
responseMap.put("msg", "다운로드 성공");
responseMap.put("data", base64str);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
responseMap.put("result", "ERROR");
responseMap.put("msg", e.getMessage());
}
return responseMap;
}
js 작성
$(function () {
// 다운로드 처리
$('#downloadBtn').on('click', function () {
let $fileNameModal = $('input[name="fileNameModal"]');
let fd = new FormData();
fd.append("fileName", $fileNameModal.val());
$.ajax({
url: "../Download",
type: 'post',
data: fd,
contentType: false,
processData: false,
cache: false,
}).done(function (data) {
const obj = JSON.parse(data);
// 성공
if (obj.result === 'OK') {
let bin = atob(obj.data.replace(/^.*,/, ''));
let buffer = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) {
buffer[i] = bin.charCodeAt(i);
}
let link = document.createElement('a');
link.download = obj.filename;
let blob = new Blob([buffer.buffer], {type: obj.mimetype});
let reader = new FileReader();
reader.readAsDataURL(blob); // blob를 base64로 변환해 onload를 호출
reader.onload = function () {
link.href = reader.result;
link.click();
};
setTimeout(function() {
location.reload();
}, 2000);
// 실패
} else if (obj.result === 'ERROR') {
// 에러 모달 표시
$('#errorModal').modal({backdrop: 'static', keyboard: false});
$("#errorMessage").text(obj.msg);
}
}).fail(function () {
// 통신 에러
$('#errorModal').modal({backdrop: 'static', keyboard: false});
$("#errorMessage").text("통신 에러 발생");
});
});
});