Java 上传文件至FTP服务器

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

大家好,欢迎来到IT知识分享网。Java

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);
        }
    }
}

路漫漫其修远兮,吾将上下而求索

译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。

如果您有什么好的想法与方法,欢迎评论区留言,我们一起讨论~

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/58350.html

(0)
上一篇 2024-05-07 15:26
下一篇 2024-05-07 19:15

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信