springboot 集成vsftp 测试

58 阅读1分钟

安装vsftp

Centos7.6 安装 FTP

导入依赖

<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.8.0</version>
</dependency>

测试类

package com.platform.iot;

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 FtpClientTest {

    public static void main(String[] args) throws IOException {
        testFtpClient();
    }

    public static void testFtpClient() throws IOException {
        FTPClient ftpClient = new FTPClient();
        //服务器地址和端口(默认是21端口)
        ftpClient.connect("yourip", 8081);
        //登录的用户名和密码
        ftpClient.login("ftpdmin", "yourpassword");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setControlEncoding("UTF-8");

        String userPath = "/ftpdmin/upload";
        String newPathname = "test";
        //读取本地文件,给出的是本地文件地址
        FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\summergao\\Desktop\\redis.conf"));
        //将路径切换到指定目录下
        boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(userPath);
        System.out.println(changeWorkingDirectory);
        //在该目录下创建该用户的文件夹
        //如果该用户的文件夹已经存在,返回值会为false
        ftpClient.makeDirectory(newPathname);
        //该用户上传的文件都传到这个目录下
        //切换目录至用户的文件夹下
        changeWorkingDirectory = ftpClient.changeWorkingDirectory(newPathname);
        System.out.println(changeWorkingDirectory);
        //设置文件类型
        boolean setFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        System.out.println(setFileType);
        //1.服务器端保存的文件名,2.上传文件的inputstream
        boolean storeFile = ftpClient.storeFile("redis.conf", inputStream);
        System.out.println(storeFile);
        ftpClient.logout();
    }

}