프로젝트

12. 공지사항 게시판 (첨부파일 다운로드)

하차모 2023. 5. 22. 22:22

첨부파일 다운로드

 

 

첨부파일 이름에 a태그를 달아주고 주소와 함께 파일 번호(pk)를 파라미터로 넘겨준다.

 

notice_detail.html

<div th:if="${#lists.size(notice.boardFileList) == 0}">
	첨부된 파일이 없습니다.
</div>
<div th:unless="${#lists.size(notice.boardFileList) == 0}"
			th:each="file : ${notice.boardFileList}">
	<a th:href="@{/notice/download(fileNum=${file.fileNum})}" style="color: black; text-decoration:underline; text-underline-offset : 5px;">
	[[${file.originFileName}]]
	</a>
	 ([[${file.fileSize}]])
</div>

 

 

NoticeController.java

//첨부파일 다운로드
@GetMapping("/download")
public void fileDownload(String fileNum, HttpServletResponse response) {
    //HttpServletResponse response 객체에 파일 정보를 담아 프론트단으로 전송

    //넘겨받은 fileNum으로 파일 정보(원본 파일명, 첨부된 파일명) 조회
    BoardFileVO downloadFile =  noticeService.getDownloadFileVO(fileNum);
    String attachedFileName = downloadFile.getAttachedFileName();
    String originFileName =  downloadFile.getOriginFileName();

    try {
        File file = new File(ConstVariable.BOARD_UPLOAD_PATH + attachedFileName);

        //File 객체의 toPath 메소드는 Path 객체를 반환
        //Files.readAllBytes() 메서드는 파일 경로를 가져와  바이트 배열로 반환
        byte[] fileByte = Files.readAllBytes(file.toPath());

        //HTTP Header 설정

        //파일 유형 설정
        response.setContentType("application/octet-stream");
        //파일 길이 설정
  	response.setContentLength(fileByte.length);

        //데이터 형식 설정
        response.setHeader("Content-Disposition",
            "attachment; fileName=\\"" + URLEncoder.encode(originFileName, "UTF-8") + "\\";");
        //인코딩 방식 설정
        response.setHeader("Content-Transfer-Encoding", "binary");

        //버퍼의 출력 스트림을 출력
        response.getOutputStream().write(fileByte);
        //버퍼에 남아있는 출력 스트림을 출력
        response.getOutputStream().flush();
        //출력 스트림 닫음
        response.getOutputStream().close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}