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

本文章概述了在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();
		}

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值