[Spring Boot] File Service (게시판에 사진 다운로드)

yihyun·2024년 9월 12일

Spring Boot

목록 보기
12/33

💾 download

웹페이지에서 파일을 다운받기 위해서는 여러 작업이 필요하다.
해당 게시글에서는 다운로드를 위한 방법을 하나씩 정리할 예정이다!

순서
1) view에 다운로드를 위한 a 태그 생성
2) controller 에서 download 메서드 생성
3) service 에서 필요한 처리 진행

✅ 1) view

<c:forEach items="${files}" var="file">
	<a href="download?new_filename=${file.new_filename}&ori_filename=${file.ori_filename}">
		<img width="500" alt="${file.ori_filename}" src="/photo/${file.new_filename}"><br/>
	</a>
</c:forEach>

→ 이미지를 누를 경우 download가 실행되며 파일의 기존이름과 새로운파일 이름을 가져온다.

✅ 2) controller

@RequestMapping(value="/download")
public ResponseEntity<Resource> download(String new_filename, String ori_filename) {
	return boardService.download(new_filename, ori_filename);
}
  • ResponseEntity<Resource> 을 반환값으로 선언한다.
    org.springframework.http<org.springframework.core.io>
  • return 값으로 실행된 결과값을 보내준다.

✅ 3) service ✨

public ResponseEntity<Resource> download(String new_filename, String ori_filename) {
	//header
    HttpHeaders header = new HttpHeaders();
		
    // body
	Resource res = new FileSystemResource("C:/upload/" + new_filename);
		
	try {
    	//header : content-type
		header.add("content-type", "application/OctetStreamData");
		String encode_name = URLEncoder.encode(ori_filename, "UTF-8");
		header.add("content-Disposition", "attachment;filename=\"" + encode_name +"\""); 
	} catch (Exception e) {
		e.printStackTrace();
	}
	return new ResponseEntity<Resource>(res, header, HttpStatus.OK); 
}

ResponseEntity<Resource>(body, header, 상태값)

  • header(사전정보) : 보낼 컨텐트 타입이 들어가 있다.
    → ❗ content-type 를 add로 넣어준다. (image, text, binary 등이 들어갈 수 있다.)
    ▷ application/octet-stream = binary 이다.
    → ❗ content-Disposition 형태를 지정해준다. ((문자 inline |파일 attachment) 파일의 경우 저장할 파일명을 지정해줘야 한다.)
    ▷ 파일명을 지정할 경우 name을 "" 로 감싸줘야 하기 때문에 이스케이프 문자를 사용해줘야 한다.
    → ❗ 파일에 한글이 있을 경우 깨질 수 있으므로 처리를 해줘야 한다.
    URLEncoder.encode(ori_filename, "UTF-8")

  • body(본문) : FileSystem 을 이용해 특정위치의 파일을 가져온다

  • 상태값 : HttpStatus.OK = 아무일 없을 경우 OK(정상) 라고 하기로 한다.
    (400, 500 등 에러를 보낼 수도 있지만 에러를 보낼 경우 에러라고 뿌려버리기 때문에 잘 사용하지 않는다.)
    200 을 적어도 된다!!

profile
개발자가 되어보자

0개의 댓글