llcong 发表于 2015-5-27 10:55:25

java+jsp代码实现从FTP服务器上传下载文件

  首先声明一下。jsp从ftp服务器上面下载文件,有两种方法
1.直接给出文件的地址
2.将文件作为字节流返回给浏览器
  
一 、先说第一种吧(这种发放很简单)。
  1.
直接使用一个超链接: 点击FTP下载
  2.
先写一个iframe


  然后
document.getElementById('downloadAudio').src = 'ftp://FTP用户名:密码@IP地址:端口号+ 后面是路径 (如:/2013/0124/20130124.wav)'
  3.
也可以直接使用window的函数:
function fileDown(){
var url = 'ftp://' + audioFtpUser + ':' + audioFtpPwd + '@' + audioServerIP + ':' + audioFtpPort + audioPath;
window.location.href = url;
};
  
二、第二种就是用java写的,然后字节流去下载
  jsp页面:
  


  
function fileDown(){
var file = Ext.getCmp('audioFileID').getValue();
document.getElementById('downloadAudio').src = securedroot+'Audio.htm?'
      + 'method=audioFileDown'
      + '&_audioServerIP='+ audioServerIP
      + '&_audioFtpPort=' + audioFtpPort
      + '&_audioFtpUser=' + audioFtpUser
      + '&_audioFtpPwd=' + audioFtpPwd
+ '&_remotePath=' + file.substring(0 , file.lastIndexOf('/') + 1)
+ '&_fileName=' + file.substring(file.lastIndexOf('/') + 1 , file.length);
};
  
  java端:
  public void audioFileDown(HttpServletRequest request, HttpServletResponse response){
String audioServerIP = request.getParameter("_audioServerIP");
int audioFtpPort = Integer.parseInt(request.getParameter("_audioFtpPort"));
String audioFtpUser = request.getParameter("_audioFtpUser");
String audioFtpPwd = request.getParameter("_audioFtpPwd");
String remotePath = request.getParameter("_remotePath");
String fileName = request.getParameter("_fileName");
LOGGER.info("连接FTP服务器,IP:" + audioServerIP + ";端口:" + audioFtpPort +";用户名:" + audioFtpUser +
";密码:" + audioFtpPwd + ";FTP路径:" + remotePath + ";文件名字:" + fileName + "。" );

//---------------------------导出音频文件-------------------------------
response.reset();
response.setContentType("application/audio/x-wav;charset=UTF-8");   //这是下载wav格式的音频用的。如果需要下载其它的文件,可以去参考一下常见的MIME类型表
response.setHeader("Content-disposition", "attachment;filename=" + fileName);

// 创建FTPClient对象
FTPClient ftp = new FTPClient();
try {
int reply;
// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.connect(audioServerIP , audioFtpPort);
ftp.login(audioFtpUser, audioFtpPwd);
ftp.setControlEncoding("UTF-8");// 设置字符编码
OutputStream out = response.getOutputStream();

reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return ;
}   
// 转到指定下载目录
ftp.changeWorkingDirectory(remotePath);
// 列出该目录下所有文件
FTPFile[] fs = ftp.listFiles();
// 遍历所有文件,找到指定的文件
for (int i = 0 ; i < fs.length ; i++){
FTPFile ff = fs ;
if (ff.getName().equals(fileName)) {
ftp.retrieveFile(ff.getName(), out) ;
out.flush();// 将缓冲区中的数据全部写出
out.close();// 关闭流
break ;
}
}
// 退出ftp
ftp.logout();
LOGGER.info("从FTP服务器下载文件成功!");
} catch (SocketException e) {
LOGGER.error("从FTP服务器下载文件失败:" + e.getMessage());
//e.printStackTrace();
} catch (IOException e) {
LOGGER.error("从FTP服务器下载文件失败:" + e.getMessage());
//e.printStackTrace();
}finally {
   if (ftp.isConnected()) {
   try {
   ftp.disconnect();
   } catch (IOException ioe) {
   LOGGER.info(ioe.getMessage());
   }
   }
   }
}
  
******************************************************************************************
以上都是在客户端下载,如果想让ftp下载到服务器端,就用下面的
  java端:
  /**
* Description: 从FTP服务器下载文件
* @param url FTP服务器hostname
* @param port   FTP服务器端口
* @param username FTP登录账号
* @param password   FTP登录密码
* @param remotePath   FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public boolean downLoadFile(String url, int port, String username,
    String password, String remotePath, String fileName,
    String localPath) {
   // 初始表示下载失败
   boolean success = false;
   // 创建FTPClient对象
   FTPClient ftp = new FTPClient();
   try {
   int reply;
   // 连接FTP服务器
   // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
   ftp.connect(url, port);
   // 登录ftp
   ftp.login(username, password);
   ftp.setControlEncoding("UTF-8");// 设置字符编码
   ftp.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置文件传输格式
   reply = ftp.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
   ftp.disconnect();
   return success;
   }   // 转到指定下载目录
   ftp.changeWorkingDirectory(remotePath);
   // 列出该目录下所有文件
   FTPFile[] fs = ftp.listFiles();
   // 遍历所有文件,找到指定的文件
   for (int i = 0 ; i < fs.length ; i++){
   FTPFile ff = fs ;
   if (ff.getName().equals(fileName)) {
// 根据绝对路径初始化文件
File localFile = new File(localPath + ff.getName());
// 获取ftp文件最后修改时间
Date fflastModifiedDate = ff.getTimestamp().getTime();
// 获取本地文件的最后修改时间
Date localLastModifiedDate = new Date(localFile.lastModified());
// result=0,两文件最后修改时间相同;result0,则相反
int result = localLastModifiedDate.compareTo(fflastModifiedDate);

if (ff.isFile()) {// 如果是文件
File lFile = new File(localPath);
lFile.mkdir();// 如果文件所在的文件夹不存在就创建
if (!lFile.exists()) {
return false;
}
if (ff.getSize() != localFile.length() || result < 0){// 如果ftp文件和本地文件大小不一样或者本地文件不存在或者ftp文件有更新,就进行创建、覆盖
FileOutputStream fos = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), fos) ;
fos.flush();// 将缓冲区中的数据全部写出
fos.close();// 关闭流
isSuccess = "文件下载成功!" ;
}else {
isSuccess = "文件已经存在!" ;
}
}
   }
   }
   // 退出ftp
   ftp.logout();
   // 下载成功
   success = true;
   } catch (IOException e) {
   LOGGER.error("从FTP服务器下载文件失败:" + e.getMessage());
   //e.printStackTrace();
   } finally {
   if (ftp.isConnected()) {
   try {
   ftp.disconnect();
   } catch (IOException ioe) {
   
   }
   }
   }
   return success;
}
  
  
************************************************************************************************
以下是从网上看来的。关于文件的下载,上传。希望对你们有用。
  一、文件上传
  文件上传源代码
    /**   
   * Description: 向FTP服务器上传文件   
   * @Version1.0   
   * @param url FTP服务器hostname   
   * @param port FTP服务器端口   
   * @param username FTP登录账号   
   * @param password FTP登录密码   
   * @param path FTP服务器保存目录   
   * @param filename 上传到FTP服务器上的文件名   
   * @param input 输入流   
   * @return 成功返回true,否则返回false   
   */   
    public static boolean uploadFile(
            String url,//FTP服务器hostname   
            int port,//FTP服务器端口
            String username, // FTP登录账号   
            String password, //FTP登录密码
            String path, //FTP服务器保存目录
            String filename, //上传到FTP服务器上的文件名   
            InputStream input // 输入流   
            ) {   
      boolean success = false;   
      FTPClient ftp = new FTPClient();   
      try {   
            int reply;   
            ftp.connect(url, port);//连接FTP服务器   
            //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器   
            ftp.login(username, password);//登录   
            reply = ftp.getReplyCode();   
            if (!FTPReply.isPositiveCompletion(reply)) {   
                ftp.disconnect();   
                return success;   
            }   
            ftp.changeWorkingDirectory(path);   
            ftp.storeFile(filename, input);            
               
            input.close();   
            ftp.logout();   
            success = true;   
      } catch (IOException e) {   
            e.printStackTrace();   
      } finally {   
            if (ftp.isConnected()) {   
                try {   
                  ftp.disconnect();   
                } catch (IOException ioe) {   
                }   
            }   
      }   
      return success;   
}   
  以下是文件上传的测试用例:
  /**
* 将本地文件上传到FTP服务器上
*
*/
public void testUpLoadFromDisk(){   
    try {   
      FileInputStream in=new FileInputStream(new File("D:/test.txt"));   
      boolean flag = uploadFile("127.0.0.1", 21, "administrator", "zyuc2011", "test", "test.txt", in);   
      System.out.println(flag);   
    } catch (FileNotFoundException e) {   
      e.printStackTrace();   
    }   
}
  /**
* 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
*
*/
public void testUpLoadFromString(){   
    try {   
      String str = "这是要写入的字符串!";
      InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));   
      boolean flag = uploadFile("127.0.0.1", 21, "administrator", "zyuc2011", "test", "test.txt", input);   
      System.out.println(flag);   
    } catch (UnsupportedEncodingException e) {   
      e.printStackTrace();   
    }   
}
  二、文件下载
  文件下载源代码
    /**   
   * Description: 从FTP服务器下载文件   
   * @Version1.0   
   * @param url FTP服务器hostname   
   * @param port FTP服务器端口   
   * @param username FTP登录账号   
   * @param password FTP登录密码   
   * @param remotePath FTP服务器上的相对路径   
   * @param fileName 要下载的文件名   
   * @param localPath 下载后保存到本地的路径   
   * @return   
   */   
    public static boolean downFile(
            String url, //FTP服务器hostname
            int port,//FTP服务器端口
            String username, //FTP登录账号
            String password, //FTP登录密码
            String remotePath,//FTP服务器上的相对路径   
            String fileName,//要下载的文件名
            String localPath//下载后保存到本地的路径
            ) {   
      boolean success = false;   
      FTPClient ftp = new FTPClient();   
      try {   
            int reply;   
            ftp.connect(url, port);   
            //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器   
            ftp.login(username, password);//登录   
            reply = ftp.getReplyCode();   
            if (!FTPReply.isPositiveCompletion(reply)) {   
                ftp.disconnect();   
                return success;   
            }   
            ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录   
            FTPFile[] fs = ftp.listFiles();   
            for(FTPFile ff:fs){   
                if(ff.getName().equals(fileName)){   
                  File localFile = new File(localPath+"/"+ff.getName());   
                  OutputStream is = new FileOutputStream(localFile);   
                  ftp.retrieveFile(ff.getName(), is);   
                  is.close();   
                }   
            }   
               
            ftp.logout();   
            success = true;   
      } catch (IOException e) {   
            e.printStackTrace();   
      } finally {   
            if (ftp.isConnected()) {   
                try {   
                  ftp.disconnect();   
                } catch (IOException ioe) {   
                }   
            }   
      }   
      return success;   
}
  以下是文件下载的测试用例:
  /**
* 将FTP服务器上文件下载到本地
*
*/
public void testDownFile(){
    try {   
      boolean flag = downFile("127.0.0.1", 21, "administrator", "zyuc2011", "test", "test.txt", "D:/");   
      System.out.println(flag);   
    } catch (Exception e) {   
      e.printStackTrace();   
    }         
}
  
  
  
  
******************************************************************************************************
提供两个网址供大家去 参考
  1.response.setContentType()中MIME参数类型总结
http://blog.iyunv.com/kanaka10/article/details/6526630
  2.Jsp/Servlet:实现文件上传与下载
http://zhangjunhd.blog.iyunv.com/113473/19631
  3.java实现FTP操作--上传,下载,删除文件
http://blog.iyunv.com/cyhgohappy/article/details/2437534
页: [1]
查看完整版本: java+jsp代码实现从FTP服务器上传下载文件