杰瑞科技汇

Java如何实现文件上传到FTP服务器?

Java 上传文件到 FTP 服务器

在 Java 中,你可以使用 Apache Commons Net 库来上传文件到 FTP 服务器,以下是完整的实现步骤和代码示例。

Java如何实现文件上传到FTP服务器?-图1
(图片来源网络,侵删)

添加依赖

确保你的项目中包含 Apache Commons Net 库,如果你使用 Maven,添加以下依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.9.0</version>
</dependency>

实现代码

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpUploader {
    /**
     * 上传文件到FTP服务器
     * @param host FTP服务器地址
     * @param port FTP服务器端口
     * @param username FTP用户名
     * @param password FTP密码
     * @param localFilePath 本地文件路径
     * @param remoteFilePath 远程文件路径
     * @return 上传成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password,
                                    String localFilePath, String remoteFilePath) {
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;
        try {
            // 连接FTP服务器
            ftpClient.connect(host, port);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
            // 登录FTP服务器
            if (!ftpClient.login(username, password)) {
                ftpClient.logout();
                return false;
            }
            // 设置文件传输模式为二进制
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 进入被动模式
            ftpClient.enterLocalPassiveMode();
            // 读取本地文件
            fis = new FileInputStream(localFilePath);
            // 上传文件
            if (!ftpClient.storeFile(remoteFilePath, fis)) {
                return false;
            }
            // 注销并断开连接
            ftpClient.logout();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        String ftpHost = "ftp.example.com";
        int ftpPort = 21;
        String ftpUsername = "username";
        String ftpPassword = "password";
        String localFilePath = "C:/local/path/to/file.txt";
        String remoteFilePath = "/remote/path/on/ftp/file.txt";
        boolean success = uploadFile(ftpHost, ftpPort, ftpUsername, ftpPassword, 
                                   localFilePath, remoteFilePath);
        if (success) {
            System.out.println("文件上传成功");
        } else {
            System.out.println("文件上传失败");
        }
    }
}

代码说明

  1. 连接FTP服务器:使用 FTPClient.connect() 方法连接到服务器,并检查连接是否成功。
  2. 登录认证:使用 login() 方法进行用户认证。
  3. 设置传输模式:使用 setFileType() 设置为二进制模式,确保文件传输的正确性。
  4. 被动模式:使用 enterLocalPassiveMode() 进入被动模式,适用于大多数网络环境。
  5. 上传文件:使用 storeFile() 方法上传文件。
  6. 资源清理:在 finally 块中确保关闭文件流和FTP连接。

高级用法

上传整个目录

如果需要上传整个目录,可以使用递归方法:

public static boolean uploadDirectory(String host, int port, String username, String password,
                                     String localDirPath, String remoteDirPath) {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(host, port);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            return false;
        }
        if (!ftpClient.login(username, password)) {
            ftpClient.logout();
            return false;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        // 创建远程目录
        if (!ftpClient.changeWorkingDirectory(remoteDirPath)) {
            if (!ftpClient.makeDirectory(remoteDirPath)) {
                return false;
            }
            ftpClient.changeWorkingDirectory(remoteDirPath);
        }
        File localDir = new File(localDirPath);
        File[] files = localDir.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归上传子目录
                    uploadDirectory(host, port, username, password, 
                                   file.getAbsolutePath(), remoteDirPath + "/" + file.getName());
                } else {
                    // 上传文件
                    FileInputStream fis = new FileInputStream(file);
                    if (!ftpClient.storeFile(file.getName(), fis)) {
                        fis.close();
                        return false;
                    }
                    fis.close();
                }
            }
        }
        ftpClient.logout();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用SSL/TLS加密连接

对于需要加密连接的情况,可以使用 FTPSClient

import org.apache.commons.net.ftp.FTPSClient;
public static boolean uploadFileSecure(String host, int port, String username, String password,
                                      String localFilePath, String remoteFilePath) {
    FTPSClient ftpsClient = new FTPSClient();
    FileInputStream fis = null;
    try {
        // 连接并设置SSL
        ftpsClient.connect(host, port);
        int reply = ftpsClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpsClient.disconnect();
            return false;
        }
        // 设置保护模式
        ftpsClient.execPBSZ(0);
        ftpsClient.execPROT("P");
        // 登录
        if (!ftpsClient.login(username, password)) {
            ftpsClient.logout();
            return false;
        }
        ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpsClient.enterLocalPassiveMode();
        fis = new FileInputStream(localFilePath);
        if (!ftpsClient.storeFile(remoteFilePath, fis)) {
            return false;
        }
        ftpsClient.logout();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (ftpsClient.isConnected()) {
                ftpsClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项

  1. 网络环境:确保你的网络环境允许与FTP服务器通信,可能需要配置防火墙。
  2. 权限:确保FTP用户有足够的权限上传文件到指定目录。
  3. 文件路径:远程文件路径应该是相对于FTP服务器的根目录的完整路径。
  4. 错误处理:在实际应用中,应该添加更详细的错误处理和日志记录。
  5. 性能考虑:对于大文件上传,可以考虑使用缓冲流提高性能。

代码提供了基本的FTP文件上传功能,你可以根据实际需求进行修改和扩展。

Java如何实现文件上传到FTP服务器?-图2
(图片来源网络,侵删)
Java如何实现文件上传到FTP服务器?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇