FTP file upload and download

Keywords: Java ftp encoding Apache Tomcat

During the development of uploading and downloading files on FTP, you can log in to the FTP server, but the upload and download always report an error. After that, the FTPClient.enterLocalPassiveMode() method is added before the operation. Success.
Note: call ftp client. Enterlocalpassivemode(); this method means that before each data connection, ftp client tells ftp server to open a port to transmit data. Why do you want to do this? Because ftp server may open different ports to transmit data each time, but on linux, due to security restrictions, some ports may not be opened, so there is a block.

Upload and download code is as follows:

public class FtpApche {
    private static FTPClient ftpClient = new FTPClient();
    private static String encoding = System.getProperty("file.encoding");

/**
  * Description: Download files from FTP server
  * 
  * @Version1.0
  * @param url
  *   FTP Server hostname
  * @param port
  *   FTP Server port
  * @param username
  *   FTP Login account
  * @param password
  *   FTP Login password
  * @param remotePath
  *   FTP Relative path on server
  * @param fileName
  *   File name to download
  * @param localPath
  *   Path saved to local after download
  * @return
 */
    public static boolean downFile(String url, int port, String username,
    String password, String remotePath, String fileName,String localPath) {
    boolean result = false;
    try {
    int reply;
    ftpClient.setControlEncoding(encoding);
    ftpClient.connect(url, port);
    // If you use the default port, you can use ftp.connect(url) to directly connect to the FTP server
    ftpClient.login(username, password);// Sign in
    // Set file transfer type to binary
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    // Get ftp login response code
    reply = ftpClient.getReplyCode();
    // Verify successful login
    if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
    System.err.println("FTP server refused connection.");
    return result;
    }
    // Transfer to FTP server directory to specified directory
    ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
    ftpClient.enterLocalPassiveMode(); 
    // Get file list
    FTPFile[] fs = ftpClient.listFiles();
    for (FTPFile ff : fs) {
    if (ff.getName().equals(fileName)) {
    File localFile = new File(localPath + "/" + ff.getName());
    OutputStream is = new FileOutputStream(localFile);
    ftpClient.retrieveFile(ff.getName(), is);
    is.close();
        }
    }
    ftpClient.logout();
    result = true;
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (ftpClient.isConnected()) {
    try {
    ftpClient.disconnect();
    } catch (IOException ioe) {
    }
    }
    }
    return result;
    }
    /**
    * Download files on FTP server to local
    * 
    */
    public void testDownFile() {
    try {
    boolean flag = downFile("132.122.237.xxx", 21, "xxx","xxx", "/home/apache-tomcat-7.0.61_2/webapps/crm/", "test.wav", "E:/");
    System.out.println(flag);
    }catch(Exception e){
        e.printStackTrace();
    }
}
    public static void main(String[] args) {

    FtpApche fa = new FtpApche();
    //download
    fa.testDownFile();
    //upload
    //fa.testUpLoadFromDisk();
    }

     public static boolean uploadFile(String url, int port, String username,
               String password, String path, String filename, InputStream input) {
              boolean result = false;
              try {
               int reply;
               // If you use the default port, you can use ftp.connect(url) to directly connect to the FTP server
               ftpClient.connect(url, port);
               // Sign in
               ftpClient.login(username, password);
               ftpClient.setControlEncoding(encoding);
               // Verify successful connection
               reply = ftpClient.getReplyCode();
               if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("connection failed");
                ftpClient.disconnect();
                return result;
               }
               // Transfer working directory to specified directory
               boolean change = ftpClient.changeWorkingDirectory(path);
               ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
               if (change) {
                ftpClient.enterLocalPassiveMode(); 
                result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
                if (result) {
                 System.out.println("Upload success!");
                }
               }
               input.close();
               ftpClient.logout();
              } catch (IOException e) {
               e.printStackTrace();
              } finally {
               if (ftpClient.isConnected()) {
                try {
                 ftpClient.disconnect();
                } catch (IOException ioe) {
                }
               }
              }
              return result;
             }
             /**
              * Upload local file to FTP server
              * 
              */
             public void testUpLoadFromDisk() {
              try {
               FileInputStream in = new FileInputStream(new File("E:/test22.wav"));
               boolean flag = uploadFile("132.122.237.xxx", 21, "xxx","xxx", "/home/apache-tomcat-7.0.61_2/webapps/crm/", "test22.txt", in);
               System.out.println(flag);
              } catch (FileNotFoundException e) {
               e.printStackTrace();
              }
             }
             }

Posted by kidsleep on Tue, 03 Dec 2019 03:34:32 -0800