From 6537ee75e52fb92a18a1e667531451f45179e7f2 Mon Sep 17 00:00:00 2001
From: wuxw <928255095@qq.com>
Date: 星期四, 03 十一月 2022 14:00:15 +0800
Subject: [PATCH] ftp 引起的不给

---
 java110-core/src/main/java/com/java110/core/client/FtpUploadTemplate.java |  160 ++++++++++++++++++++++++++++++++++++++++++++---------
 1 files changed, 133 insertions(+), 27 deletions(-)

diff --git a/java110-core/src/main/java/com/java110/core/client/FtpUploadTemplate.java b/java110-core/src/main/java/com/java110/core/client/FtpUploadTemplate.java
old mode 100644
new mode 100755
index 9ffee77..0a7445f
--- a/java110-core/src/main/java/com/java110/core/client/FtpUploadTemplate.java
+++ b/java110-core/src/main/java/com/java110/core/client/FtpUploadTemplate.java
@@ -2,13 +2,12 @@
 
 import com.java110.utils.util.Base64Convert;
 import com.java110.utils.util.DateUtil;
-import com.tencentcloudapi.tci.v20190318.models.FaceExpressionResult;
 import org.apache.commons.net.ftp.FTP;
 import org.apache.commons.net.ftp.FTPClient;
 import org.apache.commons.net.ftp.FTPFile;
 import org.apache.commons.net.ftp.FTPReply;
 import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import com.java110.core.log.LoggerFactory;
 import org.springframework.stereotype.Component;
 import org.springframework.web.multipart.MultipartFile;
 
@@ -17,6 +16,7 @@
 
 @Component
 public class FtpUploadTemplate {
+
     private static Logger logger = LoggerFactory.getLogger(FtpUploadTemplate.class);
 
     /*
@@ -25,15 +25,21 @@
      * private static String userPassword ="MXUsssMjhssE+*=a3C4\\0";//瀵嗙爜
      */
     private static String ftpPath = "uploadFiles"; // 鏂囦欢涓婁紶鐩綍
-
     private static String LOCAL_CHARSET = "GBK";
     private static String SERVER_CHARSET = "ISO-8859-1";
     private final static String localpath = "F:/";//涓嬭浇鍒癋鐩樹笅
     private final static String fileSeparator = System.getProperty("file.separator");
-
     private final static String DEFAULT_IMG_SUFFIX = ".jpg";
-
     private final static String IMAGE_DEFAULT_PATH = "img/";
+
+
+    public final static String FTP_DOMAIN = "FTP_DOMAIN";
+    public final static String FTP_SERVER = "FTP_SERVER";
+    public final static String FTP_PORT = "FTP_PORT";
+    public final static String FTP_USERNAME = "FTP_USERNAME";
+    public final static String FTP_USERPASSWORD = "FTP_USERPASSWORD";
+    public final static String FTP_PATH = "FTP_PATH";
+
 
     /*
      *鍥剧墖涓婁紶宸ュ叿鏂规硶
@@ -43,10 +49,11 @@
                          String userName, String userPassword, String ftpPath) {
         String fileName = "";
         FTPClient ftpClient = null;
+        ByteArrayInputStream is = null;
         try {
             ftpClient = new FTPClient();
             // request.setCharacterEncoding("utf-8");
-            if(!ftpClient.isConnected()){
+            if (!ftpClient.isConnected()) {
                 ftpClient.connect(server, port);
             }
             ftpClient.login(userName, userPassword);
@@ -60,7 +67,6 @@
                 LOCAL_CHARSET = "UTF-8";
             }
             fileName = UUID.randomUUID().toString();
-
             if (imageBase64.contains("data:image/png;base64,")) {
                 imageBase64 = imageBase64.replace("data:image/png;base64,", "");
                 fileName += ".png";
@@ -83,12 +89,9 @@
                 System.out.println("this file exist ftp");
                 ftpClient.deleteFile(fs[0].getName());
             }
-
-
             byte[] context = Base64Convert.base64ToByte(imageBase64);
-            ByteArrayInputStream is = new ByteArrayInputStream(context);
+            is = new ByteArrayInputStream(context);
             boolean saveFlag = ftpClient.storeFile(fileName, is);
-            is.close();
             if (!saveFlag) {
                 throw new IllegalArgumentException("瀛樺偍鏂囦欢澶辫触");
             }
@@ -98,6 +101,9 @@
         } finally {
             try {
                 ftpClient.disconnect();
+                if (is != null) {
+                    is.close();
+                }
             } catch (IOException e) {
                 e.printStackTrace();
                 logger.error("鍏抽棴ftpClient 澶辫触", e);
@@ -105,7 +111,6 @@
         }
         return IMAGE_DEFAULT_PATH + DateUtil.getNowII() + "/" + fileName;
     }
-
 
     /*
      *鏂囦欢涓婁紶宸ュ叿鏂规硶
@@ -117,7 +122,7 @@
         try {
             // request.setCharacterEncoding("utf-8");
             ftpClient = new FTPClient();
-            if(!ftpClient.isConnected()){
+            if (!ftpClient.isConnected()) {
                 ftpClient.connect(server, port);
             }
             ftpClient.login(userName, userPassword);
@@ -146,7 +151,7 @@
                 throw new IllegalArgumentException("瀛樺偍鏂囦欢澶辫触");
             }
         } catch (Exception e) {
-            // logger.error("涓婁紶鏂囦欢澶辫触", e);
+            logger.error("涓婁紶鏂囦欢澶辫触", e);
             throw new IllegalArgumentException("涓婁紶鏂囦欢澶辫触");
         } finally {
             try {
@@ -159,6 +164,59 @@
     }
 
     /*
+     *鏂囦欢涓婁紶宸ュ叿鏂规硶
+     */
+    public String upload(InputStream inputStream, String server, int port,
+                         String userName, String userPassword, String fileName) {
+        FTPClient ftpClient = null;
+        String ftpPath = "/";
+
+        if(fileName.contains("/")){
+            ftpPath = fileName.substring(0,fileName.lastIndexOf("/"));
+        }
+
+        try {
+            // request.setCharacterEncoding("utf-8");
+
+            ftpClient = new FTPClient();
+            if (!ftpClient.isConnected()) {
+                ftpClient.connect(server, port);
+            }
+            ftpClient.login(userName, userPassword);
+            ftpClient.enterLocalPassiveMode();
+            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
+            mkDir(ftpClient, ftpPath);// 鍒涘缓鐩綍
+            // 璁剧疆涓婁紶鐩綍 must
+            ftpClient.changeWorkingDirectory(ftpPath);
+            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 寮�鍚湇鍔″櫒瀵筓TF-8鐨勬敮鎸侊紝濡傛灉鏈嶅姟鍣ㄦ敮鎸佸氨鐢║TF-8缂栫爜锛屽惁鍒欏氨浣跨敤鏈湴缂栫爜锛圙BK锛�.
+                LOCAL_CHARSET = "UTF-8";
+            }
+            //fileName = new String(uploadFile.getOriginalFilename().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
+            /*fileName = id + "-" + fileName;// 鏋勫缓涓婁紶鍒版湇鍔″櫒涓婄殑鏂囦欢鍚� 20-鏂囦欢鍚�.鍚庣紑*/
+            FTPFile[] fs = ftpClient.listFiles(fileName);
+            if (fs.length == 0) {
+                System.out.println("this file not exist ftp");
+            } else if (fs.length == 1) {
+                System.out.println("this file exist ftp");
+                ftpClient.deleteFile(fs[0].getName());
+            }
+            boolean saveFlag = ftpClient.storeFile(fileName, inputStream);
+            if (!saveFlag) {
+                throw new IllegalArgumentException("瀛樺偍鏂囦欢澶辫触");
+            }
+        } catch (Exception e) {
+            logger.error("涓婁紶鏂囦欢澶辫触", e);
+            throw new IllegalArgumentException("涓婁紶鏂囦欢澶辫触");
+        } finally {
+            try {
+                ftpClient.disconnect();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return fileName;
+    }
+    /*
      *鏂囦欢涓嬭浇宸ュ叿鏂规硶
      */
     public byte[] downFileByte(String remotePath, String fileName, String server, int port, String userName, String userPassword) {
@@ -166,7 +224,7 @@
         FTPClient ftpClient = null;
         try {
             ftpClient = new FTPClient();
-            if(!ftpClient.isConnected()){
+            if (!ftpClient.isConnected()) {
                 ftpClient.connect(server, port);
             }
             ftpClient.login(userName, userPassword);
@@ -212,18 +270,18 @@
 
     public static void main(String[] args) {
         FtpUploadTemplate ftpUploadTemplate = new FtpUploadTemplate();
-        String img = ftpUploadTemplate.download("/hc/img/20200518/","ed05abae-2eca-40ff-81a8-b586ff2e6a36.jpg",
-                "118.89.243.11",617,"hcdemo","45j74jpWTf7bNhnC");
-
-        System.out.printf("img="+img);
+        String img = ftpUploadTemplate.download("/hc/img/20200518/", "ed05abae-2eca-40ff-81a8-b586ff2e6a36.jpg",
+                "118.89.243.11", 617, "hcdemo", "45j74jpWTf7bNhnC");
+        System.out.printf("img=" + img);
     }
 
     public String download(String remotePath, String fileName, String server, int port, String userName, String userPassword) {
         InputStream is = null;
         ByteArrayOutputStream bos = null;
+        ByteArrayInputStream fis = null;
         FTPClient ftpClient = new FTPClient();
         try {
-            if(!ftpClient.isConnected()){
+            if (!ftpClient.isConnected()) {
                 ftpClient.connect(server, port);
             }
             ftpClient.login(userName, userPassword);
@@ -246,11 +304,9 @@
             while (-1 != (length = is.read(buf, 0, buf.length))) {
                 bos.write(buf, 0, length);
             }
-            ByteArrayInputStream fis = new ByteArrayInputStream(
+            fis = new ByteArrayInputStream(
                     bos.toByteArray());
             bos.flush();
-            is.close();
-            bos.close();
             byte[] buffer = new byte[fis.available()];
             int offset = 0;
             int numRead = 0;
@@ -260,18 +316,32 @@
             if (offset != buffer.length) {
                 throw new IOException("Could not completely read file ");
             }
-            fis.close();
             return Base64Convert.byteToBase64(buffer);
         } catch (Exception e) {
             logger.error("ftp閫氳繃鏂囦欢鍚嶇О鑾峰彇杩滅▼鏂囦欢娴�", e);
         } finally {
-            try {
-                if(bos != null){
+            if (bos != null) {
+                try {
                     bos.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
                 }
-                if(is !=null) {
+            }
+            if (is != null) {
+                try {
                     is.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
                 }
+            }
+            if (fis != null) {
+                try {
+                    fis.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            try {
                 closeConnect(ftpClient);
             } catch (Exception e) {
                 e.printStackTrace();
@@ -330,4 +400,40 @@
         }
     }
 
+
+    public InputStream download(String fileName, String server, int port, String userName, String userPassword) {
+        InputStream is = null;
+        ByteArrayOutputStream bos = null;
+        ByteArrayInputStream fis = null;
+        FTPClient ftpClient = new FTPClient();
+        try {
+            if (!ftpClient.isConnected()) {
+                ftpClient.connect(server, port);
+            }
+            ftpClient.login(userName, userPassword);
+            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
+            ftpClient.enterLocalPassiveMode();
+            int reply = ftpClient.getReplyCode();
+            if (!FTPReply.isPositiveCompletion(reply)) {
+                ftpClient.disconnect();
+            }
+            String f = new String(
+                    (fileName).getBytes("GBK"),
+                    FTP.DEFAULT_CONTROL_ENCODING);
+            is = ftpClient.retrieveFileStream(f);// 鑾峰彇杩滅▼ftp涓婃寚瀹氭枃浠剁殑InputStream
+            if (null == is) {
+                throw new FileNotFoundException(fileName);
+            }
+
+        } catch (Exception e) {
+            logger.error("ftp閫氳繃鏂囦欢鍚嶇О鑾峰彇杩滅▼鏂囦欢娴�", e);
+        } finally {
+            try {
+                //closeConnect(ftpClient);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
 }

--
Gitblit v1.8.0