You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Apache FTPClient文件传输类型?FTP上传完整性校验需求

针对FTP上传完整性校验的解决方案

1. 跟踪当前FTP传输类型

Apache FTPClient没有提供获取当前文件传输类型的公共方法,你可以通过两种方式解决:

自行维护类型状态(推荐)

在代码中新增变量记录当前设置的文件类型,每次调用setFileType()时同步更新,避免依赖反射:

private int currentFileType = FTP.ASCII_FILE_TYPE; // 默认ASCII类型
private FTPClient ftpClient = new FTPClient();

// 封装设置文件类型的方法,同步更新状态
public void setFtpFileType(int fileType) throws IOException {
    ftpClient.setFileType(fileType);
    currentFileType = fileType;
}

反射读取内部字段

如果无法修改现有设置类型的逻辑,用反射读取FTPClient父类FTP中的_fileType字段:

public int getCurrentFileType(FTPClient ftpClient) throws NoSuchFieldException, IllegalAccessException {
    Field fileTypeField = FTP.class.getDeclaredField("_fileType");
    fileTypeField.setAccessible(true);
    return (int) fileTypeField.get(ftpClient);
}

2. 实现文件完整性校验

上传完成后,仅在二进制模式下执行大小对比校验:

// 示例上传逻辑
File localFile = new File("本地文件路径");
String remoteFilePath = "服务器文件路径";
boolean uploadSuccess = ftpClient.storeFile(remoteFilePath, new FileInputStream(localFile));

if (uploadSuccess) {
    // 仅当传输类型为二进制时校验
    if (currentFileType == FTP.BINARY_FILE_TYPE) {
        // 先确认服务器支持SIZE命令
        if (ftpClient.hasFeature("SIZE")) {
            long serverSize = ftpClient.size(remoteFilePath);
            long localSize = localFile.length();
            
            if (serverSize != localSize) {
                throw new IOException("文件上传不完整:本地大小" + localSize + ",服务器端大小" + serverSize);
            }
        }
    }
}

3. 关于TYPE命令的问题说明

直接执行TYPE命令会返回501 Missing required argument,因为FTP协议中TYPE命令必须携带参数(如TYPE I指定二进制、TYPE A指定ASCII)。且多数FTP服务器不会主动返回当前传输类型,因此不建议用这种方式判断类型。

关键注意点

  • 保留用户选择传输类型的权限,不强制二进制模式
  • 提前判断服务器是否支持SIZE命令,避免调用size()时抛出异常

内容的提问来源于stack exchange,提问作者Pramod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:20:41