Java使用FTP下载文件(将流返回给HttpServletResponse)

1.添加依赖

1
2
3
4
5
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>

2.方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static void downloadFTPFile(String path,String fileName, HttpServletResponse response){
FTPClient ftp = new FTPClient();
InputStream ins = null;
OutputStream outputStream = null;
try {
//设置连接FTP的超时时间
ftp.setConnectTimeout(1000 * 60);
//设置ftp字符集
ftp.setControlEncoding("UTF-8");
//设置为被动模式
ftp.enterLocalPassiveMode();
//登录
ftp.connect(ip, 21);
ftp.login(账号, 密码);
//验证当前登录状态
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
} else {
//转移到当前文件上一级目录下
ftp.changeWorkingDirectory(path);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
//从服务器读取指定的文件
ins = ftp.retrieveFileStream(ff.getName());
//主动调用一次getreply,解决再次读取返回null的问题
ftp.getReply();
}
}
//设置返回格式,获取到当前文件的输入流并输出
response.reset();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
outputStream = response.getOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = ins.read(b)) > 0) {
outputStream.write(b, 0, len);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ins != null) ins.close();
if (outputStream != null) outputStream.close();
//退出登录
ftp.logout();
//验证是否已连接
if (ftp.isConnected()) ftp.disconnect();
}
}