출처 : http://choija.com/217

 

웹사이트로 부터 파일을 다운받는것을 구현하는 예제입니다.
스트러츠를 쓰든, 스프링을 쓰든 로직자체는 동일합니다.

 


1) 시스템에서 평범한 html 페이지가 아닌, 어플리케이션 파일이 리턴된다고 알려주기 위해서 HpptServletResponse 를 세팅


 

response.setContentType("application/octet-stream");

response.setHeader("Content-Disposition", "attachment;filename=downloadfilename.csv");

 

attachment;filename= 구문을 통해서 다운받는 파일의 파일 이름을 초기화 시켜줄 수 있습니다

 

 

2) 유저가 파일을 웹사이트로부터 다운받게 하는 방법 2가지

 

물리적인 위치로부터 파일을 읽어들이는 경우

File file = new File("C:\\temp\\downloadfilename.csv");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
 
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();

 

 

DB의 데이터나 스트링값의 내용을 바로 다운로드 시키는 경우

 

StringBuffer sb = new StringBuffer("whatever string you like");
InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
ServletOutputStream out = response.getOutputStream();
 
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();

 

 

 

아래는 스트러츠 환경에서 유저가 "temp.csv" 파일을 다운받도록 하는 전체 예제 소스입니다.

public ActionForward export(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
 
//tell browser program going to return an application file
        //instead of html page
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=temp.csv");
 
try
{
ServletOutputStream out = response.getOutputStream();
StringBuffer sb = generateCsvFileBuffer();
 
InputStream in =
                    new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
 
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
 
  }
  return null;
}
 
private static StringBuffer generateCsvFileBuffer()
{
StringBuffer writer = new StringBuffer();
 
writer.append("DisplayName");
writer.append(',');
writer.append("Age");
writer.append(',');
writer.append("HandPhone");
writer.append('\n');
 
        writer.append("choija");
writer.append(',');
writer.append("26");
writer.append(',');
writer.append("0123456789");
writer.append('\n');
 
return writer;
}

 

+ Recent posts