Personal blog address :https://alexaccele.github.io/
First, in the Linux Install… On the server vsftpd Components
yum -y install vsftpd
Add one ftp user
This user is used to log in ftp For server .
[root@bogon ~]# useradd ftpuser
After such a user builds , You can log in with this , Remember to use normal login instead of anonymity . The default path after login is /home/ftpuser
to ftp User add password
passwd ftpuser
Firewall on 21 port
because ftp The default port is 21, and centos The default is not on , So revise iptables file
vim /etc/sysconfig/iptables
Add the following code to the file , Here I turn on 22,21,8080,6379 Wait for the port
After modification :wq After the save , restart iptables
service iptables restart
In this way, the server side is ready .
Add package dependencies
stay springboot project-engineered pom Add… To the file common-net package
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
Write test code in the test class
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);// Server address and port
ftpClient.login("ftpuser","***********");// Login username and password
// Read local file , The local file address is given
FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\123.png"));
// Set the upload path
ftpClient.changeWorkingDirectory("/home/ftpuser/images");
// Set file type
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//1. The name of the file saved on the server side ,2. Of uploaded files inputstream
ftpClient.storeFile("test.png",inputStream);
ftpClient.logout();
}
}
Run test class , Display run through
Check whether there are files on the server side
You can see that the saved path in the corresponding code has uploaded the file .