본문 바로가기
프로그래밍/java

jsp 파일 다운로드

by RPoint 2012. 9. 18.


<%

 OutputStream outStream = null;

 FileInputStream fileStream = null;

 try {

  //주소와 파일이름 가져오기

  String displayName = request.getParameter("fileName");

   

  String filePath = request.getParameter("filePath"); 

  

  response.setContentType("application/x-msdownload");

  

  //위 세팅으로 안될 경우에 사용.

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

  

  //Content-Disposition 세팅하기위해 file 이름을 변환한다.

  String Env = (String)System.getProperty("Env");

  

//  // 한글 파일 변환

      //filePath= new String(filePath.getBytes("KSC5601"));  혹은 

filePath=  new String(filePath.getBytes("8859_1"), "MS949");


// 인코딩이 필요할 경우 

     //displayName = java.net.URLEncoder.encode(displayName,"UTF-8");



  //Content-Disposition 헤더에 파일 이름 세팅.

  response.setHeader("Content-Disposition", "attachment;filename=" + displayName + ";");

  //위 세팅으로 안될 경우에 사용.

  //response.setHeader("Content-Disposition","attachment;fileName=\""+displayName+"\";");

  

  

  // 폴더에 있는 파일 가져오기 위해 다른 방법으로 변환

 

  File file = new File(filePath);

  

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

  fileStream = new FileInputStream(file);

  int i=0;

  int j=0;

  while( (i=fileStream.read()) != -1 ){

   byteStream[j] = (byte)i;

   j++;

  }

  out.clear(); //out--> jsp자체 객체

  out=pageContext.pushBody(); //out--> jsp자체 객체 

  outStream = response.getOutputStream();

  outStream.write(byteStream);

 }catch(Exception e) {

  System.out.println(e);

 }finally {

  if(fileStream != null) fileStream.close();

  if(outStream != null) outStream.close();

 }

%>

댓글