목요일, 4월 18
Shadow

#002 Spirng Framework Download

스프링으로 개발을 하면서 가장 힘들었던 부분이 어떻게 하면 데이터를 파일로 다운로드 할수 있을까 하는 부분이 아닐까 생각한다.

그러한 고민을 날려줄 소스를 공개하고자 한다.

소스코드는 의외로 간단하다.

1. Controller

@RequestMapping(value = “json/test/findOpinionVerbe” , method = RequestMethod.GET)
public String findOpinionVerbe(HttpServletRequest request,HttpServletResponse response){
String FolderName = “/test/”;
String date = new DateFormat().getCurrentWithTime();
String fileName = “opi_”+date+”.csv”;
download(FolderName, fileName, request, response);
return “common/download”;
}

2. Method

public HttpServletResponse download(String FolderName ,String fileName, HttpServletRequest request,HttpServletResponse response){
try {
String fn = FolderName;
File file = new File(fn+fileName);

FileInputStream in = new FileInputStream(file);

byte[] content = new byte[(int) file.length()];

in.read(content);

ServletContext sc = request.getSession().getServletContext();
String mimetype = sc.getMimeType(file.getName());
response.reset();
response.setContentType(mimetype);
response.setContentLength(content.length);
response.setHeader(“Content-Disposition”, “attachment; filename=\”” + file.getName() + “\””);
org.springframework.util.FileCopyUtils.copy(content, response.getOutputStream());

} catch (Exception e) {

System.out.println(e.getMessage());

}
return response;
}

3.View Page

<strong>common/download.jsp</strong>

&lt;%@ page language=”java” contentType=”text/html; charset=UTF-8″  pageEncoding=”UTF-8″%&gt; &lt;!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “<a href=”http://www.w3.org/TR/html4/loose.dtd”>http://www.w3.org/TR/html4/loose.dtd</a>”&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″&gt; &lt;title&gt;&lt;/title&gt;

&lt;/head&gt;

&lt;body onload=”self.close()”&gt; &lt;/body&gt;

&lt;/html&gt;

설명을 하자면, 1. Controller에서 request와 response 페이지를 인자값으로 입력 받게 된다. 여기서 file이름과, 폴더 이름을 입력 받아도 되지만 필자는 샘플페이지를 설명하기 위해 이미 만들어진 파일을 다운로드 하게끔 만들었다.

좀더 자세하게 설명을 하자면, /test 라는 폴더(윈도우라면c:\test\라는 폴더에 opi_2013-08-07.10.36.csv 라는 파일이 있다고 가정한다.

그리고 그 파일을 클라이언트 쪽으로 다운로드 하기 위해 download라는 메소드를 호출하게 되고 그파일을 spring의 copy라는 메소드를 사용하여 파일을 재생성 해 준다.

그리고 나서 view페이지의 common폴더의 download라는 jsp페이지를 호출하게 된다. jsp페이지가 하는 역할은 단순하게 다운로드할 파일을 다른이름으로 저장하지 않고 바로 다운로드 하게끔 만들기 위해 만들어 놓은 페이지 이다. body에 self.close() 라는 자바스크립트를 사용하게 되면 페이지가 열렸다가 바로 닫히면서 파일이 다운로드 하게 된다.

&nbsp;

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.