1
hao
2025-05-20 8e24c6fea30d9b179375ee2893710cdec2443b13
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package com.app.base.service.internal;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
 
import com.app.base.data.ApiResponseResult;
import com.app.base.service.FtpClientService;
 
@Service
public class FtpClientImpl implements FtpClientService {
    private static final Logger logger = LoggerFactory.getLogger(FtpClientImpl.class);
 
    @Autowired
    private Environment env;
 
    private FTPClient login() {
        FTPClient ftp = new FTPClient();
        try {
            FtpConfig config = getConfig();
            if (config == null) {
                return null;
            }
 
            ftp.connect(config.url, config.port);
 
            ftp.login(config.username, config.password);
            ftp.enterLocalPassiveMode();
            ftp.setFileType(2);
            ftp.setControlEncoding("gbk");
            int reply = ftp.getReplyCode();
 
            if (!FTPReply.isPositiveCompletion(reply)) {
                logger.info("FTP连接失败");
                ftp.disconnect();
                return null;
            }
            logger.info("FTP连接成功");
            return ftp;
        } catch (IOException e) {
            logger.debug("连接FTP 服务器失败.", e);
            closeCon(ftp);
        }
        return null;
    }
 
    private void closeCon(FTPClient ftp) {
        if ((ftp != null) &&
                (ftp.isConnected())) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                logger.error("关闭FTP 链接失败", e);
            }
        }
    }
 
    private FtpConfig getConfig() {
        try {
            FtpConfig ftpConfig = new FtpConfig();
            ftpConfig.url = this.env.getProperty("fs.ftp.url");
            ftpConfig.port = Integer.parseInt(this.env.getProperty("fs.ftp.port"));
            ftpConfig.username = this.env.getProperty("fs.ftp.username");
            ftpConfig.password = this.env.getProperty("fs.ftp.password");
            return ftpConfig;
        } catch (Exception e) {
            logger.error("获取FTP 配置文件失败", e);
        }
        return null;
    }
 
    public ApiResponseResult uploadFile(String path, String filename, InputStream input) {
        String url = this.env.getProperty("fs.ftp.url");
        int port = Integer.parseInt(this.env.getProperty("fs.ftp.port"));
        String username = this.env.getProperty("fs.ftp.username");
        String password = this.env.getProperty("fs.ftp.password");
        if (logger.isDebugEnabled()) {
            logger.debug("FTP 上传 url:" + url + " user name:" + username + " password:" + password);
        }
        return uploadFile(url, port, username, password, path, filename, input);
    }
 
    public ApiResponseResult uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) {
        String rootPath = this.env.getProperty("fs.ftp.rootPath", "");
        if (!StringUtils.startsWith(path, "/")) {
            path = File.separator + path;
        }
 
        String savePath = rootPath + path;
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url, port);
            ApiResponseResult localApiResponseResult1;
            if (!ftp.login(username, password)) {
                return ApiResponseResult.failure("ftp登录认证失败");
            }
 
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return ApiResponseResult.failure("上传失败");
            }
            ftp.enterLocalPassiveMode();
            ftp.setFileType(2);
            ftp.setControlEncoding("gbk");
            if (!changeWorkingDirectory(ftp, new String(savePath.getBytes("gbk"), "iso-8859-1"))) {
                return ApiResponseResult.failure("上传目录不存在或创建目录失败");
            }
            boolean success = ftp.storeFile(new String(filename.getBytes("gbk"), "iso-8859-1"), input);
 
            input.close();
            ftp.logout();
            if (!success) {
                return ApiResponseResult.failure("上传失败");
            }
            return ApiResponseResult.success("上传成功").data(path);
        } catch (IOException e) {
            boolean success;
            logger.error("ftp上传文件异常:" + savePath, e);
            return ApiResponseResult.failure("上传异常");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException localIOException7) {
                }
            }
        }
    }
 
    public ApiResponseResult download(String path, String fileName) {
        String url = this.env.getProperty("fs.ftp.url");
        int port = Integer.parseInt(this.env.getProperty("fs.ftp.port"));
        String username = this.env.getProperty("fs.ftp.username");
        String password = this.env.getProperty("fs.ftp.password");
        if (logger.isInfoEnabled()) {
            logger.info("FTP 下载 url:" + url + " user name:" + username + " password:" + password);
        }
        return download(url, port, username, password, path, fileName);
    }
 
    public ApiResponseResult download(String url, int port, String username, String password, String path, String fileName) {
        logger.info("下载地址: " + url + " port: " + port + " username: " + username + " password: " + password);
        String rootPath = this.env.getProperty("fs.ftp.rootPath", "");
        if (!StringUtils.startsWith(path, "/")) {
            path = File.separator + path;
        }
        path = rootPath + path;
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url, port);
            ApiResponseResult localApiResponseResult1;
            if (!ftp.login(username, password)) {
                return ApiResponseResult.failure("ftp登录认证失败");
            }
            logger.info("ftp 登录成功");
 
            ftp.setFileType(2);
            ftp.setControlEncoding("gbk");
            int reply = ftp.getReplyCode();
            logger.info("ftp.getReplyCode() success");
            if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("!FTPReply.isPositiveCompletion(reply)");
                ftp.disconnect();
                return ApiResponseResult.failure("下载失败");
            }
            ftp.enterLocalPassiveMode();
 
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean flag = ftp.retrieveFile(new String((path + "/" + fileName).getBytes("gbk"), "iso-8859-1"), (OutputStream) bos);
 
            logger.info("ftp.retrieveFile success");
            ApiResponseResult localApiResponseResult2;
            if (!flag) {
                return ApiResponseResult.failure("文件不存在或已被删除");
            }
            ftp.logout();
            return ApiResponseResult.success("下载成功").data(((ByteArrayOutputStream) bos).toByteArray());
        } catch (IOException e) {
            Object bos;
            logger.error("ftp下载文件异常", e);
            return ApiResponseResult.failure("下载失败");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException localIOException6) {
                }
            }
        }
    }
 
    protected boolean changeWorkingDirectory(FTPClient ftp, String path) throws IOException {
        boolean changed = ftp.changeWorkingDirectory(path);
        if (changed) {
            return true;
        }
        String[] dirs = StringUtils.split(path, "/");
        if (null == dirs) {
            return true;
        }
        String pathname = "";
        for (String dir : dirs) {
            pathname = pathname + File.separator + dir;
            if (ftp.makeDirectory(pathname)) {
                logger.debug("create ftp directory with {}", pathname);
            }
        }
 
        return ftp.changeWorkingDirectory(path);
    }
 
    public ApiResponseResult downloadFile(String path, String fileName) {
        return download(path, fileName);
    }
 
    public ApiResponseResult downloadFile(String url, int port, String username, String password, String path, String fileName) {
        return download(url, port, username, password, path, fileName);
    }
 
    public ApiResponseResult remove(String path, String fileName) {
        String ftpPath = getPath(path);
        String pathName = ftpPath + File.separator + fileName;
        logger.debug("删除FTP 文件:" + pathName);
        FTPClient ftp = login();
        if (ftp == null)
            return ApiResponseResult.failure().message("链接FTP服务器失败");
        boolean flag = false;
        if (ftp != null) {
            try {
                if (!changeWorkingDirectory(ftp, new String(ftpPath.getBytes("gbk"), "iso-8859-1"))) {
                    logger.error("切换到目录" + ftpPath + "失败,请确认目录是否存在.");
                    return ApiResponseResult.failure().message("操作失败,请确认目录是否存在.");
                }
 
                flag = ftp.deleteFile(fileName);
            } catch (IOException e) {
                logger.error("文件删除出现异常", e);
            } finally {
                closeCon(ftp);
            }
        }
        return flag ? ApiResponseResult.success() : ApiResponseResult.failure().message("文件删除失败,请检查FTP是否连接正常.");
    }
 
    public ApiResponseResult rename(String path, String fileName, String newFileName) {
        String ftpPath = getPath(path);
        logger.debug("rename ftp 文件:" + ftpPath + " fileName:" + fileName + " new fileName:" + newFileName);
        FTPClient ftpClient = login();
        boolean flag = false;
        if (ftpClient != null) {
            try {
                if (!changeWorkingDirectory(ftpClient, new String(ftpPath
                        .getBytes("gbk"), "iso-8859-1"))) {
                    logger.error("切换到目录" + ftpPath + "失败,请确认目录是否存在.");
                    return ApiResponseResult.failure().message("操作失败,请确认目录是否存在.");
                }
 
                flag = ftpClient.rename(fileName, newFileName);
            } catch (IOException e) {
                logger.error("文件重命名出现异常", e);
                closeCon(ftpClient);
            }
        }
        return flag ? ApiResponseResult.success() : ApiResponseResult.failure().message("文件重命名失败,请检查FTP是否连接正常.");
    }
 
    @Override
    public ApiResponseResult download(String url, int port, String username, String password, String path, String fileName,String root) {
        String pwd = password.replace(" ", "+");
 
        logger.info("下载地址: " + url + " port: " + port + " username: " + username + " password: " + pwd);
//        String rootPath = this.env.getProperty("fs.ftp.rootPath", "");
//        String rootPath = "/task";
        String rootPath = root;
 
        if (!StringUtils.startsWith(path, "/")) {
            path = File.separator + path;
        }
        path = rootPath + path;
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url, port);
            ApiResponseResult localApiResponseResult1;
            if (!ftp.login(username, pwd)) {
                return ApiResponseResult.failure("ftp登录认证失败");
            }
            logger.info("ftp 登录成功");
 
            ftp.setFileType(2);
            ftp.setControlEncoding("gbk");
            int reply = ftp.getReplyCode();
            logger.info("ftp.getReplyCode() success");
            if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("!FTPReply.isPositiveCompletion(reply)");
                ftp.disconnect();
                return ApiResponseResult.failure("下载失败");
            }
            ftp.enterLocalPassiveMode();
 
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean flag = ftp.retrieveFile(new String((path + "/" + fileName).getBytes("gbk"), "iso-8859-1"), (OutputStream) bos);
 
            logger.info("ftp.retrieveFile success");
            ApiResponseResult localApiResponseResult2;
            if (!flag) {
                logger.info("文件不存在或已被删除");
                return ApiResponseResult.failure("文件不存在或已被删除");
            }
            ftp.logout();
            return ApiResponseResult.success("下载成功").data(((ByteArrayOutputStream) bos).toByteArray());
        } catch (IOException e) {
            Object bos;
            logger.error("ftp下载文件异常", e);
            return ApiResponseResult.failure("下载失败");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException localIOException6) {
                }
            }
        }
    }
 
    private String getPath(String path) {
        String rootPath = this.env.getProperty("fs.ftp.rootPath", "");
        if (!StringUtils.startsWith(path, "/")) {
            path = File.separator + path;
        }
        path = rootPath + path;
        return path;
    }
 
    private class FtpConfig {
        public int port;
        public String url;
        public String username;
        public String password;
 
        private FtpConfig() {
        }
    }
}