李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
package com.chinaztt.mes.common.ftp;
 
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @Author: zhangxy
 * @Date: 2019/12/10 8:45
 */
@RefreshScope
@Component
@Data
@Slf4j
public class FtpUtils {
    private static String GSM_CONTRACT_DIR = "/contract";
    private static String GSM_ORDER_DIR = "/Order";
    private static final String UNDERLINE = "/";
 
 
    /**
     * 通过流下载
     * @param fileName
     * @param contractNumber
     * @param response
     */
    public static void downloadForWeb(String fileName, String contractNumber, HttpServletResponse response) {
        String remoteFilePath = getRemote(contractNumber) + contractNumber.replaceAll(UNDERLINE, "") + UNDERLINE + encodeFileName(fileName);
        FTPClient ftpClient = Global.pool.getResource();
        InputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = ftpClient.retrieveFileStream(remoteFilePath);
            System.out.println(is);
            bis = new BufferedInputStream(is);
            OutputStream out = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = bis.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static boolean downloadSingleFile(FTPClient ftpClient,
                                             String remoteFilePath, String savePath) throws IOException {
        File downloadFile = new File(savePath);
 
        File parentDir = downloadFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdir();
        }
 
        OutputStream outputStream = new BufferedOutputStream(
                new FileOutputStream(downloadFile));
        try {
            return ftpClient.retrieveFile(remoteFilePath, outputStream);
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
 
 
    public static void downloadDirectory(FTPClient ftpClient, String parentDir,
                                         String currentDir, String saveDir) throws IOException {
        String dirToList = parentDir;
        if (!"".equals(currentDir)) {
            dirToList += UNDERLINE + currentDir;
        }
        FTPFile[] subFiles = ftpClient.listFiles(dirToList);
        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (".".equals(currentFileName) || "..".equals(currentFileName)) {
                    continue;
                }
                String filePath = parentDir + UNDERLINE + currentDir + UNDERLINE + encodeFileName(currentFileName);
                if ("".equals(currentDir)) {
                    filePath = parentDir + UNDERLINE + encodeFileName(currentFileName);
                }
                String newDirPath = saveDir + parentDir + File.separator
                        + currentDir + File.separator + currentFileName;
                if ("".equals(currentDir)) {
                    newDirPath = saveDir + parentDir + File.separator
                            + currentFileName;
                }
                if (aFile.isDirectory()) {
                    // create the directory in saveDir
                    File newDir = new File(newDirPath);
                    boolean created = newDir.mkdirs();
                    if (!created) {
                        log.error("COULD NOT create the directory: " + newDirPath);
                    }
                    // download the sub directory
                    downloadDirectory(ftpClient, dirToList, currentFileName,
                            saveDir);
                } else {
                    // download the file
                    boolean success = downloadSingleFile(ftpClient, filePath,
                            newDirPath);
                    if (!success) {
                        log.error("COULD NOT download the file: " + filePath + ftpClient.getReplyString());
                    }
                }
            }
        }
    }
 
 
    /**
     * 获取合同对应的附件
     *
     * @param
     * @param contractNumber
     * @return
     * @throws Exception
     */
    public static List<JSONObject> getAttachmentUrlByContractId(String contractNumber) throws Exception {
        FTPClient ftpClient = Global.pool.getResource();
        List<JSONObject> list = new ArrayList<>();
        try {
            FTPFile[] files = null;
            if (ftpClient.changeWorkingDirectory(getRemote(contractNumber) + contractNumber.replaceAll(UNDERLINE, ""))) {
                files = ftpClient.listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isFile()) {
                        JSONObject attachment = new JSONObject();
                        attachment.put("name", files[i].getName());
                        list.add(attachment);
                    }
                }
            }
        } catch (Exception e) {
            log.error("过程异常!", e);
        } finally {
            Global.pool.returnResource(ftpClient);
        }
        return list;
    }
 
 
    public static boolean uploadFile(String contractNumber, String fileName, InputStream in) throws IOException {
        boolean flag = false;
        FTPClient ftpClient = Global.pool.getResource();
        if (contractNumber.indexOf(UNDERLINE) > -1) {
            ftpClient.changeWorkingDirectory(GSM_CONTRACT_DIR);
            contractNumber = contractNumber.replaceAll(UNDERLINE, "");
        } else {
            ftpClient.changeWorkingDirectory(GSM_ORDER_DIR);
        }
 
        ftpClient.mkd(contractNumber);
        boolean changedir = ftpClient.changeWorkingDirectory(contractNumber);
        if (changedir) {
            if (ftpClient.storeFile(encodeFileName(fileName), in)) {
                log.info("文件上传成功  " + fileName);
                flag = true;
            } else {
                log.error("文件上传失败  " + fileName + "  " + ftpClient.getReplyString());
            }
        }
        in.close();
        //关闭连接
        Global.pool.returnResource(ftpClient);
        return flag;
    }
 
 
    private static String encodeFileName(String fileName) {
        try {
            return new String(fileName.replaceAll(UNDERLINE, "").getBytes("UTF-8"), FTP.DEFAULT_CONTROL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }
 
 
    public static String getRemote(String contractNumber) {
        if (contractNumber.indexOf(UNDERLINE) > -1) {
            return GSM_CONTRACT_DIR + UNDERLINE;
        } else {
            return GSM_ORDER_DIR + UNDERLINE;
        }
    }
 
 
}