[JSP] 파일 다운로드
1. JSP 파일 다운로드
fileDown.jsp
<%
String idx = request.getParameter("idx");
String file_name = request.getParameter("file_name");
String file_path = "";
String ori_name = "";
HashMap<String, Object> fileList = new HashMap<String, Object>();
fileList = getNoticeFileWithIdxName(idx, file_name); // index와 file name 으로 가져옴
file_path = (String)file.get("file_path");
ori_name = (String)file.get("ori_name");
System.out.println("idx = " + idx);
System.out.println("file_path = " + file_path);
System.out.println("ori_name = " + ori_name);
BufferedInputStream buf = null;
ServletOutputStream outst= null;
try {
out.clear();
out = pageContext.pushBody();
File myfile = new File(file_path);
outst = response.getOutputStream();
String userAgent = request.getHeader("User-Agent"); // IE와 기타 브라우저 별 헤더 체크
if (userAgent.indexOf("MSIE 5.5") > -1) {
response.setHeader("Content-Disposition", "filename=" + java.net.URLEncoder.encode(ori_name, "UTF-8").replaceAll("\\+", "\\ ") + ";");
} else if (userAgent.indexOf("MSIE") > -1) { //IE
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(ori_name, "UTF-8").replaceAll("\\+", "\\ ") + ";");
} else if (userAgent.indexOf("Trident") > -1) { //IE 11
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(ori_name, "UTF-8").replaceAll("\\+", "\\ ") + ";");
} else { // etc
response.setContentType("text/plain");
response.addHeader("Content-Disposition", "attachment; filename=" + new String(ori_name.getBytes("utf-8"), "8859_1"));
response.setContentLength((int) myfile.length());
}
FileInputStream input = new FileInputStream(myfile);
buf = new BufferedInputStream(input);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
outst.write(readBytes);
}
outst.close();
buf.close();
} catch (Exception ioe) {
//ioe.printStackTrace();
}
%>
test.jsp
<a href="fileDown.jsp?idx=1&file_name=test.zip>
다운로드
</a>