关闭

jsp如何下载FTP上的文件---ftp协议方式

368人阅读 评论(0) 收藏 举报

一、创建java类:

package ftp;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.StringTokenizer;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class FtpFile {

 String serverIp = "192.168.12.49";

 String serverUser = "admin";

 String serverPwd = "admin";


 FtpClient aftp;

 DataOutputStream outputs;

 TelnetInputStream ins;

 TelnetOutputStream outs;

 int ch;

 public String a;

 String hostname = "";

 private String path = "/";


 public FtpClient connect(String RWFileDir, String hostname, int port,
   String uid, String pwd) {
  /*
   * this.hostname = hostname;
   * System.out.println("正在连接"+hostname+",请等待....."); try{ aftp = new
   * FtpClient(hostname,port); aftp.login(uid,pwd); aftp.binary();
   * //aftp.openPortDataConnection(); a = "连接主机:"+hostname+"成功!";
   * System.out.println(a); } catch(FtpLoginException e){
   * a="登陆主机:"+hostname+"失败!请检查用户名或密码是否正确:"+e; System.out.println(a);
   * //return false; } catch (IOException e){
   * a="连接主机:"+hostname+"失败!请检查端口是否正确:"+e; System.out.println(a); //return
   * false; } catch(SecurityException e) {
   * a="无权限与主机:"+hostname+"连接!请检查是否有访问权限:"+e; System.out.println(a);
   * //return false; }
   */

  // log(RWFileDir,a);
  FtpClient ftpClient = null;
  try {
   ftpClient = new FtpClient();
   // 创建FtpClient对象
   ftpClient.openServer(hostname);
   // 连接FTP服务器
   ftpClient.login(uid, pwd);
   // 登录FTP服务器
   aftp = ftpClient;
   aftp.cd(RWFileDir);
  } catch (IOException ex) {
   ;
  }
  return ftpClient;
 }

 public void stop(String RWFileDir) {
  String message = "";
  try {
   if (aftp != null) {
    aftp.closeServer();
    message = "与主机" + hostname + "连接已断开!";
    System.out.println(message);
    //log(RWFileDir, message);
   }
  } catch (IOException e) {
   message = "与主机" + hostname + "断开连接失败!" + e;
   System.out.println(message);
   log(RWFileDir, message);
  }
 }

 

 
 

 public void showFileContents(String strdir) {
  StringBuffer buf = new StringBuffer();
  try {
   aftp.cd(strdir);
   ins = aftp.list();
   while ((ch = ins.read()) >= 0) {
    buf.append((char) ch);
   }

   System.out.println("buf-------------" + buf.toString());
   ins.close();
  } catch (IOException e) {
  }
 }

 // 返回当前目录的所有文件及文件夹
 public ArrayList getFileList() throws IOException {

  BufferedReader dr = new BufferedReader(new InputStreamReader(aftp
    .list()));
  ArrayList a1 = new ArrayList(); // 存放文件
  // ArrayList a2= new ArrayList(); //存放文件夹
  ArrayList a3 = new ArrayList(); // 存放文件夹详细资料
  // ArrayList a4= new ArrayList(); //存放文件夹下其它文件夹下的文件
  ArrayList a5 = new ArrayList(); // 存放文件夹下其它文件夹下的文件
  String s = "";
  // Hashtable ha=new Hashtable();
  // ha=null;

  while ((s = dr.readLine()) != null) {

   if (isFile(s)) {
    // a4.clear();
    // a4.remove(0);
    // a4=null;
    ArrayList a4 = new ArrayList(); // 存放文件夹下其它文件夹下的文件
    a4.add(parseLine(s).get(8).toString());

    a4.add("文件");
    a4.add(parseLine(s).get(4).toString() + "bytes");
    a3.add(a4);

   }

   else if (isDir(s)) {
    // a2.add(parseLine(s).get(8));
    // showFileContents(s);
    // a3.add(parseLine(s));
    // System.out.println("ssssssss:"+s);
    // a4.add(getNameList(s));
    // a2.clear();
    // a2.remove(0);
    // a2=null;

    String tem = parseLine(s).get(8).toString();

    if ((tem.trim().equals(".")) || (tem.trim().equals(".."))) {
    } else {
     ArrayList a2 = new ArrayList(); // 存放文件夹
     a2.add(parseLine(s).get(8).toString());
     // a2.add("nbsp;");
     a2.add("文件夹");
     a2.add(parseLine(s).get(4).toString() + "bytes");
     a1.add(a2);

    }
   }

   // a1.add(parseLine(s).get(8));
   // a1.add(s);
   // System.out.println("xxxxxxxxxxxxxxxxx:"+parseLine(s).get(8));
   // a1.addAll(a2);

  }
  a5.add(a1);
  a5.add(a3);
  dr.close();
  aftp.closeServer();

  return a5;
 }

 public void setPath(String path) throws IOException {
  if (aftp == null)
   this.path = path;
  else {
   aftp.cd(path);
  }
 }

 // 返回当前目录的文件名称
 public ArrayList getNameList(String RWFileDir) throws IOException {

  // System.out.println("xxxxxxx--------------111111111");
  BufferedReader dr = new BufferedReader(new InputStreamReader(aftp
    .nameList(RWFileDir)));
  // System.out.println("xxxxxxx---------------22222222222");
  // System.out.println(dr.readLine().toString()+"ddddddddd");
  ArrayList al = new ArrayList();
  String s = "";
  int j = 0;
  while ((s = dr.readLine()) != null) {
   System.out.println(s);
   al.add(s);
   j++;
   // s = s.substring(13,s.length());
   isFile(s);
   // downloadFile(RWFileDir,s);
   // String strFileDelF = aftp.nameList("subunsubtosp//");
   // File fileDelF=new File(s);
   // fileDelF.delete();
  }
  System.out.println("xxxxxxxxxxxx" + j);
  return al;
  // System.out.println(al.add(s));
 }

 // 判断一行文件信息是否为目录
 public boolean isDir(String line) {
  return ((String) parseLine(line).get(0)).indexOf("d") != -1;
 }

 public boolean isFile(String line) {
  return !isDir(line);
 }

 // 处理getFileList取得的行信息
 private ArrayList parseLine(String line) {
  ArrayList s1 = new ArrayList();
  StringTokenizer st = new StringTokenizer(line, " ");
  while (st.hasMoreTokens()) {
   s1.add(st.nextToken());
  }
  return s1;
 }

 // 写消息日志
 public static void log(String RWFileDir, String msg) {
  String message = "";
  try {
   java.text.DateFormat df = new java.text.SimpleDateFormat(
     "yyyy-MM-dd HH:mm:ss");
   java.text.DateFormat dflog = new java.text.SimpleDateFormat(
     "yyyyMMdd");
   java.util.Date date = new java.util.Date();
   String datestr = df.format(new java.util.Date());
   String datelog = dflog.format(new java.util.Date());
   // String datelog = datestr.substring(0,10);
   // datelog = datelog.replace('-',' ');
   // 按日期每天生成一个日志文件
   FileWriter fwl = new FileWriter(RWFileDir + "CMSSftp" + datelog
     + ".log", true);
   PrintWriter outl = new PrintWriter(fwl);
   outl.println(datestr + "  " + msg);
   outl.close();
   fwl.close();
  } catch (IOException e) {
   message = "写log文件错误!" + e;
   e.printStackTrace();
   log(RWFileDir, message);
   System.out.println(message);
  }
 }

}
二、创建main.jsp页面下载文件,链接彩用ftp://用户名:密码:@IP/目录名/文件名   形式:

<%@ page language="java" contentType="text/html; charset=GB2312"%>
<%@ page import="ftp.*"%>
<%@ page import="java.util.ArrayList;"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>FTP下载主页面</title>
  <meta content="text/html; charset=gb2312" http-equiv="Content-Type">
  <link rel="stylesheet" type="text/css" href="css/list.css">
 </head>
 <body>
  <form id='list' name='list' action='post'>
   <%
     /*
     *FTP文件列表功能:从FTP上列出存在的目录及文件
     *FTP文件下载功能:从FTP上下载相应的文件
     */
    String server = "192.168.12.49"; // 输入的FTP服务器的IP地址
    String user = "admin"; // 登录FTP服务器的用户名
    String password = "admin"; // 登录FTP服务器的用户名的口令
    String path = request.getParameter("path");
    if ((path == null) || (path.length() < 1)) {
     path = "/";
    } else {
     path = new String(path.getBytes("ISO-8859-1"), "GBK"); //防止出现乱码
    }

    ArrayList arr = new ArrayList(); //用于存放根目录下的目录list和文件list
    ArrayList arr1 = new ArrayList(); //用于存放根目录下的目录list
    ArrayList arr2 = new ArrayList(); //用于存放根目录下的文件list
    ArrayList arr3 = new ArrayList(); //临时list,用于存放目录名和文件名

    FtpFile ft = null;

    try {
     ft = new FtpFile();
     ft.connect(path, server, 21, user, password);
     arr = ft.getFileList(); //获取根目录文件夹列表
    } catch (Exception ex) {
     System.out.println(ex.toString());

    }
    arr1 = (ArrayList) arr.get(0);
    arr2 = (ArrayList) arr.get(1);
    out
      .print("<font size='4'><center><b>FTP 文 件 列 表</b></center></font><br>");
    out.print("<table style='width:80%' align='center'><tr>");

    out.print("<td align='left'><font size='2' color='red'>*当前位置:"
      + path + "</font></td>");

    out
      .print("<td align='right'><input type='button' align='right' value='返回上一页' onClick='history.go(-1)'></td>");
    out
      .println("<table border=0 cellPadding='5' cellSpacing='2' class='listtable' align='center' style='width:80%'><tr class='firstline'><td width='200px'align='center'>文件名</td><td width='60px' align='center'>类型</td><td width='100' align='center'>大小</td><td align='center'>下载</td></tr>");

    for (int i = 0; i < arr1.size(); i++) { //取出文件夹

     arr3 = (ArrayList) arr1.get(i);
     out.print("<tr class='line'>");
     for (int j = 0; j < arr3.size(); j++) {
      out.print("<td><B>");
      String tempstr = arr3.get(j).toString();
      if (j == 0) {
     if (path.length() > 1) {
      out.print("<a href='main.jsp?path=" + path + "/"
      + tempstr + "'>" + tempstr + "</a>");
     } else {
      out.print("<a href='main.jsp?path=" + path
      + tempstr + "'>" + tempstr + "</a>");
     }

      } else {
     out.print(tempstr);
      }
      out.print("</B></td>");
     }
     out.print("<td>&nbsp;</td></tr>");

    }
    String filename = null;
    for (int i = 0; i < arr2.size(); i++) { //取出文件
     arr3 = (ArrayList) arr2.get(i);
     out.print("<tr class='line'>");
     for (int j = 0; j < arr3.size(); j++) {
      out.print("<td>");

      String tempstr = arr3.get(j).toString();
      if (j == 0) {
     filename = tempstr;
     if (path.trim().length() > 1) { //如果path带有下级有子文件
      out.print("<a href='ftp://" + user + ":" + password
      + "@" + server + path + "/" + filename
      + "'>" + tempstr + "</a>");
     } else { //path只是根目录
      out.print("<a href='ftp://" + user + ":" + password
      + "@" + server + path + filename + "'>"
      + tempstr + "</a>");
     }
      } else {
     out.print(tempstr);
      }
      out.print("</td>");
     }
     if (path.trim().length() > 1) { //如果path带有下级有子文件
      out
      .print("<td width='100px' align='center'><a href='ftp://"
      + user
      + ":"
      + password
      + "@"
      + server
      + path
      + "/"
      + filename
      + "'>下载</a></td></tr>");
     } else { //path只是根目录
      out
      .print("<td width='100px' align='center'><a href='ftp://"
      + user
      + ":"
      + password
      + "@"
      + server
      + path + filename + "'>下 载</a></td></tr>");
     }
    }
    out.print("</table>");
    ft.stop(path);
    ft = null;
   %>
  </form>
 </body>
</html>


 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12832次
    • 积分:150
    • 等级:
    • 排名:千里之外
    • 原创:0篇
    • 转载:13篇
    • 译文:0篇
    • 评论:3条
    文章存档
    最新评论