<%@ page contentType="application/download;charset=KSC5601" %>
<%@ page import="java.io.*" %>
<%
response.setContentType("application/download");
//String fileName = "tomcat.gif";
String fileName = "RELEASE-NOTES.txt";
//아래처럼 attachment 를 사용하면 브라우저는 무조건 다운로드 창을 띄우고 파일명을 보여준다.
response.setHeader("Content-Disposition", "attachment;filename="+fileName+";");
ServletOutputStream sos = null;
try{
sos = response.getOutputStream();
}catch(Exception e){e.printStackTrace();}
//다음과 같이 스트림을 열고 브라우저에 바이트 데이터를 전송해주면 된다.
FileInputStream fio = null;
byte[] buf = new byte[1024];
fio = new FileInputStream("C:/Tomcat5.5/webapps/ROOT/"+fileName);
int n = 0;
while((n=fio.read(buf, 0, buf.length))!=-1) {
sos.write(buf, 0, n);
sos.flush();
}
sos.close();
%>
응용예제
download.html
<HTML>
<HEAD>
<TITLE> Download example </TITLE>
</HEAD>
<BODY><br><br><br><center>
파일을 다운로드 하는 방법에 따른 효과<hr width=70%>
<table>
<tr>
<td>
<a href="RELEASE-NOTES.txt">RELEASE-NOTES.txt 링크</a>
<td>
텍스트 파일을 하이퍼 링크(href)로 연결한 경우
<tr>
<td>
<a href="download2.jsp?num=1">RELEASE-NOTES.txt 다운로드</a>
<td>
텍스트 파일을 Stream으로 전송하는 경우
<tr>
<td>
<a href="tomcat.gif">tomcat.gif 링크</a>
<td>
이미지 파일을 하이퍼 링크(href)로 연결한 경우
<tr>
<td>
<a href="download2.jsp?num=2">tomcat.gif 다운로드</a>
<td>
이미지 파일을 Stream으로 전송하는 경우
</table>
</center>
</BODY>
</HTML>
download.jsp
<%@ page contentType="application/download;charset=KSC5601" %>
<%@ page import="java.io.*" %>
<%
String num = request.getParameter("num");
response.setContentType("application/download");
String fileName = null;
if(num.equals("1")) fileName = "RELEASE-NOTES.txt";
else if(num.equals("2")) fileName = "tomcat.gif";
//아래처럼 attachment 를 사용하면 브라우저는 무조건 다운로드 창을 띄우고 파일명을 보여준다.
response.setHeader("Content-Disposition", "attachment;filename="+fileName+";");
ServletOutputStream sos = null;
try{
sos = response.getOutputStream();
}catch(Exception e){e.printStackTrace();}
//다음과 같이 스트림을 열고 브라우저에 바이트 데이터를 전송해주면 된다.
FileInputStream fio = null;
byte[] buf = new byte[1024];
fio = new FileInputStream("C:/Tomcat5.5/webapps/ROOT/"+fileName);
int n = 0;
while((n=fio.read(buf, 0, buf.length))!=-1) {
sos.write(buf, 0, n);
sos.flush();
}
sos.close();
%>