Post

스프링 Single File Download Resolver

스프링 Single File Download Resolver

웹 프로젝트 개발을 하다보면 업로드한 파일을 다운로드하는 모듈을 요청 받을 때가 있다.
해당되는 파일을 컨트롤러에서 바로 구현을 해도 되겠지만, 스프링 ViewResolver로 구현을 하면 같은 프로젝트의 모든 개발들이 쉽게 사용할 수 있다.

스프링 ViewResolver는 AbstractView를 상속받아서 구현 할 수 있다.

FileDownViewResolver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@Component("fileDownLoadView")
public class FileDownView extends AbstractView{
  private FileInputStream fin = null;
  private BufferedInputStream bis = null;
  private ServletOutputStream sout = null;
  private BufferedOutputStream bos = null;

  @Override
  protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    // 다운로드 받을 때 저장할 파일명
    String fileName = (String) model.get("fileName");
    // 다운로드 받을 파일경로
    String filePath = (String) model.get("filePath");

    response.setContentType("application/octet-stream;");
    File file = new File(filePath);
    try{
      if(file.exists()){
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"),"ISO8859_1") + ";");

        byte buff[] = new byte[2048];
        int bytesRead;

        fin = new FileInputStream(file);
        bis = new BufferedInputStream(fin);
        sout = response.getOutputStream();
        bos = new BufferedOutputStream(sout);

        while((bytesRead = bis.read(buff)) != -1){
          bos.write(buff, 0, bytesRead);
	}

	bos.flush();

	fin.close();
	sout.close();
	bis.close();
	bos.close();
      }else{
        // 자체 예외발생
       	throw new Exception("해당 파일이 존재하지 않습니다.");
      }
    }catch(CSFWException e){
      throw e;
    }catch(Exception e){
      // 자체 예외발생
      throw new CSFWException("파일 다운로드중에 오류가 발생하였습니다.");
    }finally{
      if(fin != null){fin.close();}
      if(sout != null){sout.close();}
      if(bis != null){bis.close();}
      if(bos != null){bos.close();}
    }
  }
}

스프링에서 ViewResolver로 사용하기 위해서는 xml을 통해서 등록을 해야 하지만, @Component 어노테이션을 사용한다면 별도의 설정없이 바로 사용할 수 있다.

컨트롤러에서 사용하는 방법

1
2
3
4
5
6
@RequestMapping("fileDownload.do")
public String fileDonwLoadSample(ModelMap model) throws Exception{
  model.put("fileName", "저장할 파일명");
  model.put("filePath", "다운로드 할 파일의 풀 경로");
  return "fileDownLoadView";
}
This post is licensed under CC BY 4.0 by the author.