Java上传文件至FTP服务器

1、问题:
在项目开发过程中,遇到需要将页面上选择的文件上传至FTP服务器,遇到一些坑,比如上传文件中文名乱码,上传时指定上传目录不能自动创建等问题。

2、FTP上传文件工具类

public class FtpUtil {
    private String hostname = "xxx";
    private Integer port = 21 ;
    private String username = "xxx";
    private String password = "xxx";
    private FTPClient client = null;

    public String initialize() throws Exception{
        client = new FTPClient();
        client.setControlEncoding("utf-8");
        client.connect(hostname, port);
        client.login(username, password);
        int replyCode = client.getReplyCode();
        if(!FTPReply.isPositiveCompletion(replyCode))
            return "Connect ftp failed";

        return "success";
    }

    public String uploadFile(String storePath, String fileName, String uploadFile) throws Exception {
        InputStream stream = new FileInputStream(new File(uploadFile));
        client.setFileType(client.BINARY_FILE_TYPE);
        this.prepareStorePath(client, storePath);
        client.sendCommand("OPTS UTF8", "ON");
        client.storeFile(fileName, stream);
        if (client.storeFile(fileName, stream))
            return "Upload file success";

        return "Upload file failed";
    }

    private void prepareStorePath(FTPClient client, String storePath) throws Exception{
        String[] split = storePath.split("\\\\");

        for (String str : split) {
            if (StringUtils.isBlank(str))
                continue;

            if (!client.changeWorkingDirectory(str)) {
                client.makeDirectory(str);
                client.changeWorkingDirectory(str);
            }
        }
    }
}

3、Application.java测试上传

public class Application {
    public static void main(String[] args) throws Exception {
        FtpUtil ftp = new FtpUtil();
        ftp.initialize();
        ftp.uploadFile("uploads", "W3School离线手册2017.chm", "F:\\ToolFile\\W3School离线手册2017.chm");
    }
}

4、文件名中文乱码解决办法:

client.sendCommand("OPTS UTF8", "ON");

5、指定文件存储目录不能创建解决办法:

private void prepareStorePath(FTPClient client, String storePath) throws Exception{
    String[] split = storePath.split("\\\\");

    for (String str : split) {
        if (StringUtils.isBlank(str))
            continue;

        if (!client.changeWorkingDirectory(str)) {
            client.makeDirectory(str);
            client.changeWorkingDirectory(str);
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java上传文件FTP服务器的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FTPUploader { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String username = "your-username"; String password = "your-password"; File fileToUpload = new File("path/to/file.txt"); // 要上传的文件路径 FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FileInputStream fileInputStream = new FileInputStream(fileToUpload); String remoteFile = "uploaded-file.txt"; // 远程服务器上保存的文件名 boolean uploaded = ftpClient.storeFile(remoteFile, fileInputStream); fileInputStream.close(); if (uploaded) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败!"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 以上代码使用了Apache Commons Net库来处理FTP相关操作。你需要将`server`、`port`、`username`和`password`替换为你的FTP服务器的相关信息,将`fileToUpload`替换为你要上传的文件路径,`remoteFile`替换为在服务器上保存的文件名。 请确保你的项目中包含了Apache Commons Net库的依赖。你可以在Maven项目中添加以下依赖: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.8.0</version> </dependency> ``` 希望对你有所帮助!如果有任何问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值