파일 다운로드를 하기위해서는 업로드할때 경로와 파일이름을 알아야 한다.
file을 통해 받은 파일경로를 FileInputStream 통해 받고 while문을 통해 조금씩 다운을 받을수 있다.
@WebServlet("/FileDown")
String filePath = currentDirPath + "\\" + fileName; // 파일경로
File file = new File(filePath);
System.out.println(filePath); //파일 경로를 알수있다
try {
OutputStream out = response.getOutputStream();
response.setHeader("Cache-Control", "no-chche");
response.addHeader("Cache-Control", "no-store");
response.setHeader("Content-disposition", "attachment; fileName=\"" + URLEncoder.encode(fileName,"UTF-8") + "\";");
//다운받을시 한글깨짐방지를 방지한다
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024*8];
while(true) {
int count = in.read(buffer);
if(count == -1) {
break;
}
out.write(buffer, 0, count);;
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
이후 View 페이지를 통해 다운받을수 있다.
<body>
<h1>index.jsp 다운로드</h1>
<body>
<h2>${requestScope.fileName} File Download</h2>
파일명 : <a href = "FileDown?fileName=${requestScope.fileName }">${requestScope.fileName }</a>
</body>
파일 업로드 / 다운로드 구현 (1) - 파일 업로드 (0) | 2021.01.11 |
---|