Java 上传文件到FTP服务器

依赖的包

commons-net 包

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

使用方法

    /**
     * @param hostname    ftp 服务器ip
     * @param port        ftp服务器端口号
     * @param username    用户名
     * @param password    密码
     * @param basePath    ftp服务器根路径
     * @param inputStream 文件输入流
     * @param remote      ftp远程服务器文件名
     * @return 是否上传成功
     * @throws IOException
     */
    public static boolean uploadFile(String hostname, int port, String username, String password, String basePath, FileInputStream inputStream, String remote) throws IOException {
        //1、创建一个FtpClient对象
        FTPClient ftpClient = new FTPClient();

        //2、创建FTP连接
        ftpClient.connect(hostname, port);

        //3、登录FTP 服务器,使用用户名密码
        ftpClient.login(username, password);

        //4、上传文件
        // FTPClient默认是 字符串,会将二进制转为 utf-8字符串。
        // 上传二进制文件
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //切换路径,这样可以将文件上传到此路径,否则会上传到根路径
        ftpClient.changeWorkingDirectory(basePath);
        boolean re = ftpClient.storeFile(remote, inputStream);

        //5、关闭连接
        ftpClient.logout();

        return re;
    }
  • 测试代码

     @Test
        public void testFTPClient() throws IOException {
    
    
            String hostname = "192.168.43.106";
            int port = 21;
            String username = "ftpuser";
            String password = "123456";
            String basePath = "/home/ftpuser/www/img";
            File imageFile = new File("/Users/liujian/Desktop/timg.jpg");
            FileInputStream inputStream = new FileInputStream(imageFile);
            String remote = "mv.jpg";
    
            boolean f = FTPClientUtils.uploadFile(hostname, port, username, password, basePath, inputStream, remote);
            if (f) {
                System.out.println("上传成功");
            } else {
                System.out.println("上传失败");
            }
    
        }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值