Administrator
2022-06-06 b6820f509709e4499ceffec0664959027e7df37f
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package org.springblade.modules.FTP;
 
import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.net.SocketException;
import java.util.Date;
import java.util.Map;
 
import net.lingala.zip4j.core.ZipFile;
 
import static org.springblade.common.config.FtpConfig.*;
 
/**
 * ftp工具类
 *
 * @author lijj
 */
 
public class FtpUtil {
 
    private final static Log logger = LogFactory.getLog(FtpUtil.class);
    /**
     * 本地字符编码
     */
    private static String LOCAL_CHARSET = "GBK";
 
    // FTP协议里面,规定文件名编码为iso-8859-1
    private static String SERVER_CHARSET = "ISO-8859-1";
 
    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPasswordOut FTP 登录密码
     * @param ftpUserNameOut FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserNameOut, String ftpPasswordOut) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserNameOut, ftpPasswordOut);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
//                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }
 
    /**
     * 从FTP服务器下载文件
     *
     * @param ftpHost     FTP IP地址
     * @param ftpUserNameOut FTP 用户名
     * @param ftpPasswordOut FTP用户名密码
     * @param ftpPort     FTP端口
     * @param ftpPath     FTP服务器中文件所在路径 格式: ftptest/aa
     * @param localPath   下载到本地的位置 格式:H:/download
     * @param fileName    文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserNameOut, String ftpPasswordOut, int ftpPort,
                                       String ftpPath, String localPath, String fileName) {
 
        FTPClient ftpClient = null;
 
        try {
            ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut);
            // 设置上传文件的类型为二进制类型
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            // 上传文件
            //对中文文件名进行转码,否则中文名称的文件下载失败
            String fileNameTemp = new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            ftpClient.changeWorkingDirectory(ftpPath);
 
            InputStream retrieveFileStream = ftpClient.retrieveFileStream(fileNameTemp);
 
            // 第一种方式下载文件(推荐)
            //File localFile = new File(localPath + File.separatorChar + fileName);
            //OutputStream os = new FileOutputStream(localFile);
            //ftpClient.retrieveFile(fileName, os); os.close();
 
 
            // 第二种方式下载:将输入流转成字节,再生成文件,这种方式方便将字节数组直接返回给前台jsp页面
            byte[] input2byte = input2byte(retrieveFileStream);
            byte2File(input2byte, localPath, fileName);
 
            if (null != retrieveFileStream) {
                retrieveFileStream.close();
            }
        } catch (FileNotFoundException e) {
            logger.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            logger.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误。");
            e.printStackTrace();
        } finally {
 
            if (ftpClient.isConnected()) {
                try {
                    //退出登录
                    ftpClient.logout();
                    //关闭连接
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
 
 
    public static boolean uploadFile(String ftpHost, int ftpPort, String ftpUserNameOut, String ftpPasswordOut,
                                     String basePath, String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftpClient = null;
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return result;
            }
            // 切换到上传目录
            if (!ftpClient.changeWorkingDirectory(basePath + filePath)) {
                // 如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir))
                        continue;
                    tempPath += "/" + dir;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            // 设置上传文件的类型为二进制类型
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            // 上传文件
            filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            if (!ftpClient.storeFile(filename, input)) {
                return result;
            }
 
            if (null != input) {
                input.close();
            }
 
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    //退出登录
                    ftpClient.logout();
                    //关闭连接
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
 
 
    public static boolean deleteFile(String ftpHost, int ftpPort, String ftpUserNameOut, String ftpPasswordOut, String pathname,
                                     String filename) {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut);
            // 验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                return flag;
            }
            // 切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            // 设置上传文件的类型为二进制类型
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            //对中文名称进行转码
            filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            ftpClient.dele(filename);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    //退出登录
                    ftpClient.logout();
                    //关闭连接
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
        return flag;
    }
 
    // 将字节数组转换为输入流
    public static final InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }
 
    // 将输入流转为byte[]
    public static final byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
 
    // 将byte[]转为文件
    public static void byte2File(byte[] buf, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     *
     * 解压zip 包
     * @author panchaoyuan
     * @param srcFile    Unzipped file
     * @param destDirPath   Unzipped destination folder
     * @throws RuntimeException
     * @throws IOException
     */
    public static void unZip(MultipartFile srcFile, String destDirPath, String savePath) throws RuntimeException, IOException {
        File file = null;
        InputStream ins = srcFile.getInputStream();
        String savaPaths = savePath+srcFile.getOriginalFilename();
        file=new File(savaPaths);
        inputStreamToFile(ins, file);
 
        if (!file.exists()) {
            throw new RuntimeException(file.getPath() + ",file is not found");
        }
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(file);
//            zipFile.setFileNameCharset("utf-8");
            zipFile.setFileNameCharset("gbk");
            //解压到 destDirPath
            zipFile.extractAll(destDirPath);
        }catch(Exception e) {
            throw new RuntimeException("unzip error from FileUtil", e);
        }
    }
 
 
    /**
     * 输入流转换为文件
     * @author panchaoyuan
     * @return
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 执行sql 上传
     * @param obj sql
     */
    public static void sqlFileUpload(String obj){
        String json1 = JSON.toJSONString(obj);
        String response1 = String.valueOf((new Date()).getTime());
        OutJson.createJsonFile(json1, localPath, "nq"+response1);
        FileInputStream in1 = null;
        try {
            in1 = new FileInputStream(new File(localPath + "nq"+response1+".json"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut, ftpPath, "/",  "nq"+response1+".json", in1);
        MysqlCenlint.deletess("nq"+response1+".json");
    }
 
    /**
     * 执行 对象数据(用户,报名对象信息等) 上传
     * @param obj 对象信息
     */
    public static void objectFileUpload(Object obj){
        String json1 = JSON.toJSONString(obj);
        String response1 = String.valueOf((new Date()).getTime());
        OutJson.createJsonFile(json1, localPath, "ni"+response1);
        FileInputStream in1 = null;
        try {
            in1 = new FileInputStream(new File(localPath + "ni"+response1+".json"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut, ftpPath, "/",  "ni"+response1+".json", in1);
        System.out.println("用户新增,向外网推送数据结束.................");
        MysqlCenlint.deletess("ni"+response1+".json");
    }
 
 
    /**
     * 执行 对象数据(用户,报名对象信息等) 上传
     * @param obj 对象信息
     */
    public static void objectFileUploadList(Object obj){
        String json1 = JSON.toJSONString(obj);
        String response1 = String.valueOf((new Date()).getTime());
        OutJson.createJsonFile(json1, localPath, "nl"+response1);
        FileInputStream in1 = null;
        try {
            in1 = new FileInputStream(new File(localPath + "nl"+response1+".json"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut, ftpPath, "/",  "nl"+response1+".json", in1);
        MysqlCenlint.deletess("nl"+response1+".json");
    }
 
    /**
     * 返回报名信息结果
     * @param obj
     */
    public static void objectFileUploadListTrain(Object obj){
        String json1 = JSON.toJSONString(obj);
        String response1 = String.valueOf((new Date()).getTime());
        OutJson.createJsonFile(json1, localPath, "nt"+response1);
        FileInputStream in1 = null;
        try {
            in1 = new FileInputStream(new File(localPath + "nt"+response1+".json"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut, ftpPath, "/",  "nt"+response1+".json", in1);
        MysqlCenlint.deletess("nt"+response1+".json");
    }
 
    /**
     * 向外网发送保安员证编号位数数据
     * @param obj
     */
    public static void objectFileUploadSecurityNumberCount(Object obj){
        String json1 = JSON.toJSONString(obj);
        String response1 = String.valueOf((new Date()).getTime());
        OutJson.createJsonFile(json1, localPath, "ns"+response1);
        FileInputStream in1 = null;
        try {
            in1 = new FileInputStream(new File(localPath + "ns"+response1+".json"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserNameOut, ftpPasswordOut, ftpPath, "/",  "ns"+response1+".json", in1);
        MysqlCenlint.deletess("ns"+response1+".json");
    }
}