2010/JAVA(jsp)2010. 11. 9. 14:27


<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URLDecoder"%><%@ page contentType="text/html; charset=euc-kr" pageEncoding="EUC-KR" import="java.io.*"%>
<%
 //주소와 파일이름 가져오기
 request.setCharacterEncoding("euc-kr");


 
final String filePath = "/WRAP/report/";
String filePath2 = request.getParameter("fpath");
filePath2 = URLDecoder.decode(filePath2);


String fileName = filePath2+"/"+filePath2+"_"+ URLDecoder.decode(request.getParameter("fnm"))+".pdf";

  //또는 아래 사용
 //String filePath = request.getRealPath("/")+"uploadFile/";
 //System.out.println(filePath);
 
 //응답 헤더의 Content-Type을 세팅한다.
 response.setContentType("application/x-msdownload;charset=euc-kr");
 //위 세팅으로 안될 경우에 사용.
// response.setContentType("application/octet-stream");
 
 //Content-Disposition 세팅하기위해 file 이름을 변환한다.
 //String convName1 = new String(fileName.getBytes("euc-kr"), "8859_1"); //windows xp 기준- 한글
 //java.net.URLEncoder.encode(new String(fileName.getBytes("euc-kr"), "8859_1"),"UTF-8");

 //Content-Disposition 헤더에 파일 이름 세팅.
 response.setHeader("Content-Disposition", "attachment;filename=" + request.getParameter("fnm")+".pdf"+ ";");
 
 //위 세팅으로 안될 경우에 사용.
 //response.setHeader("Content-Disposition","attachment;fileName=\""+Convfilename+"\";");
 
 // 폴더에 있는 파일 가져오기 위해 다른 방법으로 변환
 //String  convName2 = new String(fileName .getBytes("euc-kr"), "euc-kr");
 //String  convName2 = new String(fileName .getBytes("8859_1"), "euc-kr");
 File file = new File(filePath+fileName);
 // 사용자에게 보내주기 위해 스트림객체 생성
 byte b[] = new byte[(int)file.length()];
 if (file.length() > 0 && file.isFile()) // 0byte이상이고, 해당 파일이 존재할 경우
 {
   BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));

   // 인풋객체생성
   BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());

   // 응답객체생성
   
  int read = 0;
  try {
   while ((read = fin.read(b)) != -1){
       outs.write(b,0,read);
   }
   outs.flush();
   outs.close();
   fin.close();
  } catch (Exception e) {
   System.out.println("download error : " + e.getMessage());
  } finally {
   if(outs!=null) outs.close();
   if(fin!=null) fin.close();
  }
 }

 /* 위 내용대신 아래내용을 써도 무방.같은 결과: byte b[]부분부터 대체
 byte[] byteStream = new byte[(int)file.length()];
 FileInputStream fileStream = new FileInputStream(file);
 int i=0;
 int j=0;
 while( (i=fileStream.read()) != -1 ){
  byteStream[j] = (byte)i;
  j++;
 }
 OutputStream outStream = response.getOutputStream();
 outStream.write(byteStream);
 outStream.close();
 */
%>




Posted by penguindori