BACK-END/Spring
[Spring] 사진 클릭했을때 사진 다운로드하기
단비_danbee
2020. 10. 13. 23:38
img태그를 클릭하면 사진이 다운로드 할 수 있는 기능을 구현했다.
| BoardDetail.jsp
a태그안의 전달하는 값을 살펴보자.
${pageContext.request.contextPath} 는 현재 프로젝트의 경로
/resources/upload/ 는 사진이 들어있는 폴더의 경로
${dto.img_file_name} 는 파일의 실제 이름 (예 : abc.jpg)
filePath와 fileName을 컨트롤러에 있는 photoDownload.do 메소드로 보내주었다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[boardList.jsp]</title>
<style type="text/css">
*{font-size: 12pt; font-weight: bold; }
a{text-decoration:none;font-size: 12pt; font-weight: bold; color:blue ;}
a:hover{font-size: 12pt; font-weight: bold; text-decoration:underline; color:green ; }
</style>
</head>
<body>
<font color=blue>[boardDetail.jsp]</font> <br>
<a href="photoDownload.do?filePath=${pageContext.request.contextPath}/resources/upload/&fileName=${dto.img_file_name}&idx=${hobby_idx}">
<img src ='${pageContext.request.contextPath}/resources/upload/${dto.img_file_name}' width=150 height=50 border=0>
</a>
</body>
</html>
| ControllerBoardController.java
@Inject
@Autowired
ServletContext application;
@Inject
@Autowired
BoardServiceImp bs; /* 내용은 없고 함수만 선언되어 있는 인터페이스타입으로 접근 */
@Inject
@Autowired
BoardDAO dao;
@RequestMapping("/photoDownload.do")
public void photoDownload(@RequestParam String filePath,@RequestParam String fileName, HttpServletResponse response) {//extends IOException
String fullPath = filePath+fileName;
System.out.println("파일경로 : "+ fullPath);
String path = application.getRealPath("/resources/upload");
File file = new File(path, fileName);
try {
//다운로드 정보 표시하는 팝업창 역할
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") );
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] bt = new byte[(int)file.length()] ; //byte타입은 1바이트타입
is.read(bt,0,bt.length);
os.write(bt);
is.close();
os.close();
} catch (Exception e) {System.out.println("에러 : "+e);}
}