ch.0 2022. 10. 31. 19:05


파일 다운로드

 

1. 뷰 영역 변경

 

		<div class="file_list">
			<a th:each="list : ${board.fileList}" th:href="@{/board/downloadBoardFile.do(idx=${list.idx}, boardIdx=${list.boardIdx})}" th:text="|${list.originalFileName} (${list.fileSize} kb)|"></a>
		</div>

링크를 추가 설정

 

 

2. SQL 추가

	<select id="selectBoardFileInformation" parameterType="map" resultType="board.board.dto.BoardFileDto">
		<![CDATA[
			SELECT
				original_file_name,
				stored_file_path,
				file_size
			FROM
				t_file
			WHERE
				idx = #{idx}
				AND board_idx = #{boardIdx}
				AND deleted_yn = 'N'
		]]>
	</select>

기존과 다르게 DTO 가 아닌 map을 사용함. 이유는 단순히 파라미터 전달만을 위한 목적이기 때문.

 

 

3. 서비스 및 매퍼 추가

 

BoardService.java

	BoardFileDto selectBoardFileInformation(int idx, int boardIdx) throws Exception;

BoardServiceImpl.java

	@Override
	public BoardFileDto selectBoardFileInformation(int idx, int boardIdx) throws Exception {
		return boardMapper.selectBoardFileInformation(idx, boardIdx);
	}

BoardMapper.java

	BoardFileDto selectBoardFileInformation(@Param("idx") int idx, @Param("boardIdx" )int boardIdx);

마이바티스는 map을 파라미터로 사용하는 기능을 지원한다. 개발하다 보면 쿼리의 파라미터가 2~3개인 경우 이를 위해 DTO를 만들기 애매한 경우가 있다. 이럴때 @Param 어노테이션을 이용하면 해당 파라미터들이 map에 저장된다.

 

 

4. 컨트롤러 추가

	@RequestMapping("/board/downloadBoardFile.do")
	public void downloadBoardFile(@RequestParam int idx, @RequestParam int boardIdx, HttpServletResponse response) throws Exception{
		BoardFileDto boardFile = boardService.selectBoardFileInformation(idx, boardIdx);
		if(ObjectUtils.isEmpty(boardFile) == false) {
			String fileName = boardFile.getOriginalFileName();
			
			byte[] files = FileUtils.readFileToByteArray(new File(boardFile.getStoredFilePath()));
			
			response.setContentType("application/octet-stream");
			response.setContentLength(files.length);
			response.setHeader("Content-Disposition", "attachment; fileName=\"" + URLEncoder.encode(fileName,"UTF-8")+"\";");
			response.setHeader("Content-Transfer-Encoding", "binary");
			
			response.getOutputStream().write(files);
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
	}

2: HttpServletResponse 객체를 파라미터로 사용한다. 사용자로부터 들어오는 모든 요청 정보를 담고 있는 HttpServletRequest 클래스와 반대로 사용자에게 전달할 데이터만 담고 있다.

HttpServlerResponse 클래스에 적정히 설정을 해 주면 사용자에게 전달할 결괏값을 원하는 대로 만들거나 변경할 수 있다.

3: 데이터베이스에서 선택된 파일의 정보를 조회한다.

7: storedFilePath 값으로 실제 파일 정보를 읽어온 후 byte[] 형태로 변환한다

 

 

 

 

 

 

6장을 마치며..

파일 업로드와 다운로드에 대해서 알아봤다.

서비스와 마찬가지로 뷰 - 서비스&매퍼 - 컨트롤 로 구성되었고 전체적인 흐름에 대해서 복습하는 느낌이였다.