1. Introduce dependencies:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.3</version> <scope>compile</scope> </dependency>
2. Define configuration information in application.yml:
spring: ftp: IP: 192.168.40.138 port: 14147 username: root password: 123456 path: D:/filezillawork
3. Define configuration class:
import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.net.SocketException; /** * FTP server configuration */ @Data @Slf4j @Configuration public class FtpConfig { /** * FTP IP address */ @Value("${spring.ftp.ip}") private String ip; /** * FTP port number */ @Value("${spring.ftp.port}") private Integer port; /** * FTP login account */ @Value("${spring.ftp.username}") private String username; /** * FTP login password */ @Value("${spring.ftp.password}") private String password; /** * FTP working path */ @Value("${spring.ftp.path}") private String path; private FTPClient ftpClient; /** * Connect to FTP service */ public FTPClient connect() { ftpClient = new FTPClient(); try { //Set encoding ftpClient.setControlEncoding("UTF-8"); //Set the connection timeout (unit: milliseconds) ftpClient.setConnectTimeout(10 * 1000); // connect ftpClient.connect(ip, port); // Log in ftpClient.login(username, password); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { log.error("Not connected to FTP, wrong username or password"); //reject connection ftpClient.disconnect(); } else { log.info("Connected to FTP successfully"); //Set binary mode to transfer files ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //Set passive working mode ftpClient.enterLocalPassiveMode(); } return ftpClient; } catch (SocketException e) { e.printStackTrace(); log.error("FTP IP address error"); } catch (IOException e) { e.printStackTrace(); log.error("FTP port error"); } return ftpClient; } /** * Disconnect FTP service */ public void closeConnect() { log.warn("Close ftp server"); try { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } }
4. Define tool classes for easy use
import com.boyia.ftpdemov2.config.FtpConfig; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.springframework.stereotype.Component; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Slf4j @Component @RequiredArgsConstructor public class FtpUtil { private final FtpConfig ftpConfig; public static final String DIR_SPLIT = "/"; /** * Get FTPClient * @return FTPClient */ private FTPClient getFTPClient() { FTPClient ftpClient = ftpConfig.connect(); if (ftpClient == null || !FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new RuntimeException("ftp client exception"); } return ftpClient; } /** * Get all file names in a specific directory from FTP * * @param ftpDirPath Destination file path on FTP */ public List<String> getFileNameList(String ftpDirPath) { FTPClient ftpClient = getFTPClient(); try { // Get the FTPFile file list through the provided file path // FTPFile[] ftpFiles = ftpClient.listFiles(ftpDirPath, FTPFile::isFile); // Get only files // FTPFile[] ftpFiles = ftpClient.listFiles(ftpDirPath, FTPFile::isDirectory); // Get only the directory FTPFile[] ftpFiles = ftpClient.listFiles(ftpDirPath); if (ftpFiles != null & amp; & ftpFiles.length > 0) { return Arrays.stream(ftpFiles).map(FTPFile::getName).collect(Collectors.toList()); } log.error(String.format("The path is wrong, or the directory [%s] is empty", ftpDirPath)); } catch (IOException e) { log.error("File acquisition exception:", e); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * upload files * * @param uploadPath upload path * @param fileName file name * @param input file input stream * @return upload result */ public boolean upload(String uploadPath, String fileName, InputStream input) { FTPClient ftpClient = getFTPClient(); try { //Switch to working directory if (!ftpClient.changeWorkingDirectory(uploadPath)) { ftpClient.makeDirectory(uploadPath); ftpClient.changeWorkingDirectory(uploadPath); } // file writing boolean storeFile = ftpClient.storeFile(fileName, input); if (storeFile) { log.info("File: {} uploaded successfully", fileName); } else { throw new RuntimeException("ftp file writing exception"); } ftpClient.logout(); return true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (input != null) { input.close(); } if (ftpClient.isConnected()) { ftpClient.disconnect(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return false; } /** * download file * * * @param ftpPath FTP server file directory * * @param ftpFileName file name * * @param localPath The downloaded file path * * @return */ public boolean download(String ftpPath, String ftpFileName, String localPath) { FTPClient ftpClient = getFTPClient(); OutputStream outputStream = null; try { FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath, file -> file.isFile() & amp; & amp; file.getName().equals(ftpFileName)); if (ftpFiles != null & amp; & ftpFiles.length > 0) { FTPFile ftpFile = ftpFiles[0]; File localFile = new File(localPath + DIR_SPLIT + ftpFile.getName()); // Determine whether the local path directory exists, create it if it does not exist if (!localFile.getParentFile().exists()) { localFile.getParentFile().mkdirs(); } outputStream = Files.newOutputStream(localFile.toPath()); ftpClient.retrieveFile(ftpFile.getName(), outputStream); log.info("fileName:{},size:{}", ftpFile.getName(), ftpFile.getSize()); log.info("Download file successfully..."); return true; } else { log.info("The file does not exist, filePathname:{},", ftpPath + DIR_SPLIT + ftpFileName); } } catch (Exception e) { log.error("Failed to download file..."); e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return false; } /** * Delete files or directories from FTP server * The directory where the file exists cannot be deleted * * @param ftpPath server file storage path * @param fileName server file storage name * @return delete result */ public boolean delete(String ftpPath, String fileName) { FTPClient ftpClient = getFTPClient(); try { // Get file information in the ftp directory whose file name matches fileName FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath, file -> file.getName().equals(fileName)); // Delete Files if (ftpFiles != null & amp; & ftpFiles.length > 0) { boolean del; String deleteFilePath = ftpPath + DIR_SPLIT + fileName; FTPFile ftpFile = ftpFiles[0]; if (ftpFile.isDirectory()) { del = ftpClient.removeDirectory(deleteFilePath); } else { del = ftpClient.deleteFile(deleteFilePath); } log.info(del ? "File: {} deleted successfully" : "File: {} deleted", fileName); return del; } else { log.warn("File: {} not found", fileName); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return false; } }
5. Use ftp to operate files
Note: The root directory “./” here is equivalent to the FTP shared folder directory
@RestController @RequestMapping("/ftp") @RequiredArgsConstructor public class FtpController { private final FtpUtil ftpUtil; private static final String ROOT_DIR = "./"; @GetMapping("/getFileNameList") public List<String> getFileNameList() { return ftpUtil.getFileNameList(ROOT_DIR); } @PostMapping("/upload") public boolean uploadToFtpServer(MultipartFile file) throws IOException { //Read file information String fileName = file.getOriginalFilename(); InputStream fileInputStream = file.getInputStream(); //Upload files to Ftp service return ftpUtil.upload(ROOT_DIR, fileName, fileInputStream); } @GetMapping("/download") public boolean download(){ String localPath = "C:/Users/A/Desktop/243.jpg", ftpFileName = "330.png"; return ftpUtil.download(ROOT_DIR, ftpFileName, localPath); } @GetMapping("/delete") public boolean delete(String fileName){ return ftpUtil.delete(ROOT_DIR, fileName); } }
Reprinted from: https://blog.csdn.net/m0_51985332/article/details/128895145
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139,296 people are learning the system