romworld

Spring 16 - LPROD에 파일 다운로드 하기 본문

Spring

Spring 16 - LPROD에 파일 다운로드 하기

inderrom 2023. 2. 2. 17:41

<detail.jsp>

  • 모달창에 다운로드 버튼을 만든다.
<!-- Modal -->
<div class="modal fade" id="modal-default" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">첨부파일</h1>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" id="btnDownload" class="btn btn-secondary" >다운로드</button>
        <button type="button" id="modalClose" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

 

하단에 스크립트 수정

  • sessionStorage.setItem("filename",filename);
  • session은 JSP 내장 객체 / sessionStorage는 클라이언트
  • <iframe id="ifrm" name="ifrm" style="display:none;"></iframe>
<iframe id="ifrm" name="ifrm" style="display:none;"></iframe>
<script type="text/javascript">
$(function(){
	//모달 닫기
	$("#modalClose").on("click", function(){
		$("#modal-default").modal("hide");
	});
	// 이미지 목록의 보기를 클릭 시 정보들을 모달창으로 보냄
	$(".btn-outline-primary").on("click", function(){
		//달러(this) : 클래스로 요소들을 선택했으므로
		let filename = $(this).data("filename");
		console.log("filename : " + filename);
		
		/* sessionStorage
		- 세션 스토리지는 각각의 URL에 대해 독립적인 저장 공간을 제공함
		- 저장 공간이 쿠키보다 큼
		- session은 JSP 내장 객체 / sessionStorage는 클라이언트(쿠키처림)
		*/
		//session.setAttribute("filename",filename);
		sessionStorage.setItem("filename",filename);
		
		//modal-body 클래스인 요소에 이미지를 보이자(html은 새로고침, append는 누적)
		//<div class="modal-body"></div>
		$(".modal-body").html("<img src='/resources/upload" + filename + 
				"' style='width:100%' />")
	});
	
	// 파일 다운로드 하기
	$("#btnDownload").on("click",function(){
		let fnm = sessionStorage.getItem("filename");
		console.log("fnm : " + fnm);
		//<iframe id="ifrm" name="ifrm" style="display:none;"></iframe>
		let vIfrm = document.getElementById("ifrm");
		vIfrm.src = "/download?fileName="+fnm;
	});
})
</script>

 

DownloadController 를 만들어주자

<DownloadController.java>

package kr.or.ddit.util;

import java.io.UnsupportedEncodingException;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class DownloadController {
	// 요청URI : 요청URI : http://localhost/download?fileName=/2023/01/30/파일명.jpg
	// 요청파라미터 :fileName=/2023/01/30/파일명.jpg
	@ResponseBody
	@GetMapping("/download")
	public ResponseEntity<Resource> download(@RequestParam String fileName){
		log.info("fileName : " + fileName );
		
		// resource : 다운로드 받을 파일(자원)
		// 만들어둔 upload 파일이 있는 경로를 적어준다.
		//	"C:\\eclipse_202006\\workspace\\springProj\\src\\main\\webapp\\resources\\upload\\"
		// + fileName   ==> upload 뒤에 \\ 를 뺀다면 + 이 아니라 , 를 적어주면 된다.
		Resource resource = new FileSystemResource(
				"C:\\eclipse_202006\\workspace\\springProj\\src\\main\\webapp\\resources\\upload\\"
				+ fileName
				);
		String resourceName = resource.getFilename();
		// header : 인코딩 정보, 파일명 정보
		HttpHeaders headers = new HttpHeaders();
		//Content-Disposition : 다운로드 창 열기
		try {
			headers.add("Content-Disposition", "attachment;filename=" +
					new String(resourceName.getBytes("UTF-8"), "ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			log.info(e.getMessage());
			e.printStackTrace();
		}
		
		return new ResponseEntity<Resource>(resource, headers, HttpStatus.OK);
	}
}

Comments