Please Enable JavaScript!
Gon[ Enable JavaScript ]

web application 에서 ftp 파일을 Client 브라우저에 전송

자바(JAVA)
반응형

이 아티클에 주요 내용은 web application 환경에서 Ftp와 연결해 가져온 파일을 어떻게

Client 로 전송하는 것인지에 대한 내용이다.

 

sun.net.ftp.FtpClient  를 상속받아 만든 FtpFileClient 객체를 생성한다.

FtpFileClient Ftp 관리를 편하게 하기위해 내가 만든 클래스 이다.

get() 함수를 통해 InputStream 객체를 가져온다. 이 객체를 통해서 Ftp 가져온 파일을 읽어들인다. 이렇게 읽어들인 값을 HttpServletResponse OutputStream 을 가져온뒤거기에 담아 보내면된다.

그전에 HttpServletResponse  ContentType값이나 기타 Header 값들을 셋팅한다.

 

그리고 전송을 마친후 Stream 객체를 닫아주고 ftp 도 연결을 종료한다.

 

String ip = "162.222.134.15";

String port = "21";

String id = "gon";

String pwd = "1111";

 

String orgName = "ftpFile.txt";

String path = "/path";

 

FtpFileClient ftp = null;

InputStream in = null;

OutputStream out = null;

 

try {

    ftp = new FtpFileClient(ip, port);

    ftp.connectFtp(id, pwd);

    ftp.binary();

   

    String ftpPath = path + "/" + orgName;

    in = ftp.get(ftpPath);

                

    // HttpServletResponse 에서 OutputStream 객체를 가져온다.

    out = response.getOutputStream();

    // HttpServletResponse 전송객체에 Header 값을셋팅한다.

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

    response.setHeader("Content-Transfer-Encoding;", "base64");

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

        new String(orgName.getBytes("euc-kr"),"8859_1") + ";");

                   

    // FtpFileClient 에서 읽어온 InputStream 객체를 이용해

    // 파일을 읽어온뒤 response 객체에 넣는다.

    byte b[] = new byte[1024];

    int numRead = 0;

    int totalRead = 0;

    out = response.getOutputStream();

   

    while ((numRead = in.read(b)) != -1){

        out.write(b, 0, numRead);

        totalRead += numRead;

    }

    // 파일크기를 셋팅한다.

    response.setContentLength(totalRead);

   

    out.flush();

} catch (Exception e) {

    e.printStackTrace();

} finally{

    in.close();

    out.close();

    ftp.disconnect();

}


반응형
Posted by 녹두장군1
,