在springboot中使用vsftpd实现文件上传到服务器

首先在Linux服务器中安装vsftpd组件

 yum -y install vsftpd

添加一个ftp用户

此用户就是用来登录ftp服务器用的。

[root@bogon ~]# useradd ftpuser

这样一个用户建完,可以用这个登录,记得用普通登录不要用匿名了。登录后默认的路径为 /home/ftpuser

 

给ftp用户添加密码

passwd ftpuser

 

防火墙开启21端口

因为ftp默认的端口为21,而centos默认是没有开启的,所以要修改iptables文件

vim /etc/sysconfig/iptables

在文件中添加如下代码,这里我开启了22,21,8080,6379等端口

修改后:wq保存后,重启iptables

service iptables restart

这样服务器端的准备就做好了。

添加包依赖

在springboot项目工程的pom文件中添加 common-net 包

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

在测试类中编写测试代码

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FTPTest {

    @Test
    public void testFtpClient() throws IOException {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect("118.**.**.***",21);//服务器地址和端口
        ftpClient.login("ftpuser","***********");//登录的用户名和密码
        //读取本地文件,给出的是本地文件地址
        FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\123.png"));
        //设置上传路径
        ftpClient.changeWorkingDirectory("/home/ftpuser/images");
        //设置文件类型
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //1.服务器端保存的文件名,2.上传文件的inputstream
        ftpClient.storeFile("test.png",inputStream);
        ftpClient.logout();
    }
}

运行测试类,显示运行通过

检查服务器端是否有文件存在

可以看到对应代码中的保存路径已经有了上传的文件。

猜你喜欢

转载自blog.csdn.net/qq_40995335/article/details/81408937
今日推荐