프로젝트 정리/Naver Boost Course

파일 다운로드 구현하기

학습 목표

  1. 파일을 다운로드 하는 컨트롤러를 작성할 수 있다.

핵심 개념

  • response.setHeader
  • Content-Disposition
  • Content-Type
  • Content-Length
  • 제공하는 connect.png 파일을 윈도우 사용자의 경우 c:/tmp/ 디렉토리에 복사하고 맥 사용자의 경우는 /tmp 디렉토리에 복사합니다.
  • FileController에 download메소드를 추가합니다.
    • response에 header를 설정합니다.
    • 파일을 outputStream으로 출력합니다.
  • http://localhost:8080/guestbook/download를 브라우저에서 입력하면 파일이 다운되는 것을 확인할 수 있습니다.
@GetMapping("/download")
	public void download(HttpServletResponse response) {

		// 직접 파일 정보를 변수에 저장해 놨지만, 이 부분이 db에서 읽어왔다고 가정한다.
		String fileName = "connect.png";
		String saveFileName = "c:/tmp/connect.png"; // 맥일 경우 "/tmp/connect.png" 로 수정
		String contentType = "image/png";
		int fileLength = 1116303;

		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		response.setHeader("Content-Type", contentType);
		response.setHeader("Content-Length", "" + fileLength);
		response.setHeader("Pragma", "no-cache;");
		response.setHeader("Expires", "-1;");

		try(
				FileInputStream fis = new FileInputStream(saveFileName);
				OutputStream out = response.getOutputStream();
				){
			int readCount = 0;
			byte[] buffer = new byte[1024];
			while((readCount = fis.read(buffer)) != -1){
				out.write(buffer,0,readCount);
			}
		}catch(Exception ex){
			throw new RuntimeException("file Save Error");
		}
	}

이 역시 실제 프로젝트에서 구현해 보자

 

생각해보기

  1. 파일 다운로드를 구현할 때는 보안에 상당히 신경을 싸야 합니다. 인자로 파일명을 받아들여, 그 파일명을 다운로드 받게 할 경우 해커들은 파일명을 "../../etc/passwd" 와 같은 형태로 전달하여 해킹을 시도하게 하는 경우도 있습니다.

참고 자료

[제공 이미지] connect.png

 

[참고링크] Spring MVC 4 File Download Example - WebSystique

http://websystique.com

[참고링크] Spring MVC 4 - File download example

https://www.boraji.com

 

'프로젝트 정리 > Naver Boost Course' 카테고리의 다른 글

BE_PJT F-1. 예약관리 시스템: 한줄평  (0) 2021.04.22
파일 업로드 구현하기  (0) 2021.04.20
파일업로드 컨셉설명  (0) 2021.04.18
slf4j를 이용한 로그남기기  (0) 2021.04.15
slf4j 설정하기  (0) 2021.04.15