낭만 프로그래머
Spring MVC 5와 Javascript를 이용한 파일(File) 다운로드(Download) 본문
일반적으로 서버에 있는 파일을 다운로드 할 경우 JSP를 사용하였다. 현재 Spring MVC 5로 작업을 하다보니 Javascript를 이용하여 서버의 Controller 호출하려 한다.
처음에는 ajax를 이용하여 호출을 해보려 했으나 2번을 호출해야 한다는 점도 있고 해서 아래와 같이 간단하게 작업을 해 보았다.
APIController.java
@RequestMapping(value = "/actionExcelDownload.do", method = RequestMethod.GET)
public ResponseEntity<Resource> actionExcelDownload(
		@RequestParam(value = "fileName",required = false) String fileName) {
	Resource resource = null;
	try {
		// 서버의 물리적 파일패스
		String tempFilePath = "c:\\temp\\1234567.xlsx";
		Path tempFile = Paths.get(tempFilePath);
		resource = new UrlResource(tempFile.toUri());
		// 임시파일을 지우기 위해서
		new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(100000);
                    Path tempFilePath = Paths.get(tempFilePath);
					Files.delete(tempFilePath);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	catch(Exception e) {
		e.printStackTrace();
	}
	fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
	fileName = fileName.replaceAll("\\+", "%20");
	return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
			"attachment; filename=\"" + fileName + "\"").body(resource);
}
actionList.jsp
<script>
	function excelDownload(e) {
            var fileName = "한글로 가자.xlsx";
            const encFileName = encodeURI(fileName);
            window.location = '<%=applicationBasePath%>/api/actionExcelDownload.do?fileName='+encFileName;
        }
</script>
<!-- Kendo UI 관련된 것임 -->
<script id="excelDownloadTemplate" type="text/x-kendo-template">
	<a class="k-button" href='javascript:void(0)' onclick="excelDownload(event)">Excel Download</a>
</script>'Java > Spring' 카테고리의 다른 글
| Spring MVC 5 에서 Spring Scheduler 사용하기 (0) | 2021.12.14 | 
|---|---|
| Spring + Mybatis에서 트랜젝션(Transaction) 처리 (0) | 2021.12.06 | 
| Intellij에 Spring MVC 5 설치하기 (0) | 2021.09.28 | 
| Spring Boot 기본 세팅 (DB + Mybatis + Log4j2) (0) | 2020.11.04 | 
| JSP에서 Invalid character 관련하여 400 에러가 발생시 (0) | 2020.04.14 | 
 
                  