你好,游客 登录 注册 搜索
背景:
阅读新闻

利用Apache提供的ftp下载工具类下载ftpServer数据

[日期:2013-01-12] 来源:Linux社区  作者:shihuacai [字体: ]

本文章概述了在B/S模式下,从FTP服务器上读取数据,并利用struts2框架下载的关键代码

private static FTPClient ftpClient = new FTPClient();


// 连接ftp服务器

private boolean connectServer(String ip, String user, String password) {
//FTP服务器的IP地址;user:登录FTP服务器的用户名;password:登录FTP服务器的用户名的口令;path:FTP服务器上的
// 路径
try {
ftpClient.connect(ip);
ftpClient.login(user, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//指定文件类型,解决下载后文件大小变化的问题
} catch (Exception e1) {
e1.printStackTrace();
}
return true;

}

 


private void downloadSingleFile(String ip, String username, String pwd, String filePath, String fileName, String fileType)
throws IOException {
// 连接ftp
connectServer(ip, username, pwd);

//解决中文路径的问题
filePath = new String(filePath.getBytes("GBK"), "iso-8859-1");
fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
ftpClient.changeWorkingDirectory(filePath);
InputStream is = ftpClient.retrieveFileStream(fileName);

//下载文件
download(is, fileName, fileType);
}

 

 

//利用struts下载

public void download(InputStream brSource, String fileName, String fileType) {
HttpServletResponse res = ServletActionContext.getResponse();
try {
if (brSource == null) {
String url = this.getRequest().getScheme() + "://" + this.getRequest().getServerName() + ":"
+ this.getRequest().getServerPort() + this.getRequest().getContextPath() + "/" + "fileNotFound.jsp";
this.getResponse().sendRedirect(url);
return;
}
// InputStream brSource = new BufferedInputStream(new FileInputStream(file));
int len = 0;
// 清空输出流
res.reset();
// 设定输出文件头
res.setContentType("application/x-" + fileType + "-compressed;charset=utf-8");
res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1"));
// res.addHeader("Content-Length", ""+brSource.available());
OutputStream out = new BufferedOutputStream(res.getOutputStream());
int i = 0;
byte[] buffer = new byte[800];
while (true) {
if (brSource.available() < 800) {
while (i != -1) {
i = brSource.read();
out.write(i);
}
break;
} else {
brSource.read(buffer);
out.write(buffer);


}
}
brSource.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}


}

linux
相关资讯       Apache FtpServer  FtpServer 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款