728x90

스프링으로 간단하게 파일 다운로드 구현



1.파일 경로와 이름을 가진 File 객체 생성


2.response.setContentType으로 다운로드와 문자셋 설정하고

길이도 등록


3.파일이름을 URLEncoder로 utf-8로 인코딩후

response.setHeader로 파일이름을 헤더에 등록


4.클라이언트에게 전송하기 위한

OutputStream out = response.getOutputStream();

출력스트림 개설


5. 출력할 파일을 읽기 위해 File 객체를 읽는

FileInputStream fis = new FileInputStream(fis);


FileInputStream 객체 생성


6.스프링에서 제공하는

FileCopyUtils를 이용하여 복사

FileCopyUtils.copy(fis,out)


7.파일 입력 스트림을 닫고

출력 스트림을 flush


fis.close();

out.flush



 @RequestMapping("photoDownload")
 public void photoDownload(HttpServletRequest request, HttpServletResponse response) throws Exception{
  
  String photoName = request.getParameter("name");
  
  String sep = File.separator;
  System.out.println("sep : " + sep);
  
  String filePath = "C:"+sep+"Users"+sep+"do"+sep+"git"+sep+"Project01"+sep+"src"+sep+"main"+sep+"webapp"+sep+"resources"+sep+"uploaded";
 
  File file = new File(filePath,photoName);
  
  //다운을 위한 컨텐츠 타입을 설정
  response.setContentType("application/download;charset=utf-8");
  response.setContentLength((int)file.length());
  
  //전송되는 파일이름을 그대로 보내주기 위한 설정
  
  //한글 파일명을 클라이언트로 보내려면 URLEncoding이 필요
  photoName = URLEncoder.encode(photoName, "UTF-8");
  
  response.setHeader("Content-Disposition",
    "attachment;fileName=\""+photoName+"\";");
  
  
  //클라이언트에게 보내기 위해 응답 스트림을 구함
  OutputStream out = response.getOutputStream();
  
  /*
  FileInputStream을 통해 클라이언트로 보낼 파일을 읽어
  스프링이 제공하는 FileCopyUtils 클래스를 통해 데이터를 읽고
  스트림을 통해 클라이언트로 출력한다.
  
  */
  FileInputStream fis = null;
  
  fis = new FileInputStream(file);
  FileCopyUtils.copy(fis, out);
  
  fis.close();
  
  out.flush();
 }

300x250

+ Recent posts