[JSP] 파일 다운로드

2015. 3. 4. 14:44프로그래밍/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>

'프로그래밍 > Jsp' 카테고리의 다른 글

[JSTL] JSTL 데이터 타입 확인  (0) 2015.06.30
[JSP] 페이징 채번  (0) 2015.03.04
[Jsp] Jsp 페이징처리  (0) 2015.02.25
[Jsp] Jsp 페이징처리  (0) 2014.04.02
[Jsp] Jsp 엑셀 다운로드  (0) 2014.03.31