java ftp传输文件

概要

整体架构流程

在pom文件中加载依赖

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

技术细节

    public void FtpUpload(String localFilePath, String title) {

        localFilePath = downloadPrefix + localFilePath;

        try {
            FTPClient ftpClient = new FTPClient();
            // 连接FTP服务器
            ftpClient.connect(ftpUrl, Integer.parseInt(port));
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode(); // 使用被动模式
            ftpClient.setControlEncoding("UTF-8"); // 设置控制连接的编码
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置文件传输类型为二进制

            // 读取远程文件并上传到FTP
            // 文件流放在try中,执行完之后系统会自动把文件流关闭
            try (BufferedInputStream fileInputStream = new BufferedInputStream(new URL(localFilePath).openStream())) {

                LocalDateTime now = LocalDateTime.now();
                int year = now.getYear();
                int monthValue = now.getMonthValue();
                int dayOfMonth = now.getDayOfMonth();

                String remoteFilePath = "/" + year + "-" + monthValue + "-" + dayOfMonth;

                if (!ftpClient.changeWorkingDirectory(remoteFilePath)) {
                    ftpClient.makeDirectory(remoteFilePath);
                }

                String[] split = localFilePath.split("\\.");
                String path = remoteFilePath + "/" + title + "." + split[split.length - 1];

                // 将中文文件名转换为服务器编码
                String encodedRemoteFilePath = new String(path.getBytes("UTF-8"), "ISO-8859-1");

                boolean uploadSuccess = ftpClient.storeFile(encodedRemoteFilePath, fileInputStream);
                if (uploadSuccess) {
                    log.info("文件上传成功");
                } else {
                    log.info("文件上传失败");
                }
            }
            // 完成后,登出并关闭连接
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

需要注意路径问题,容易导致失败

小结

碧蓝幻想yyds

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值