概要
整体架构流程
在pom文件中加载依赖
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
技术细节
public void FtpUpload(String localFilePath, String title) {
localFilePath = downloadPrefix + localFilePath;
try {
FTPClient ftpClient = new FTPClient();
// 连接FTP服务器
ftpClient.connect(ftpUrl, Integer.parseInt(port));
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode(); // 使用被动模式
ftpClient.setControlEncoding("UTF-8"); // 设置控制连接的编码
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置文件传输类型为二进制
// 读取远程文件并上传到FTP
// 文件流放在try中,执行完之后系统会自动把文件流关闭
try (BufferedInputStream fileInputStream = new BufferedInputStream(new URL(localFilePath).openStream())) {
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int monthValue = now.getMonthValue();
int dayOfMonth = now.getDayOfMonth();
String remoteFilePath = "/" + year + "-" + monthValue + "-" + dayOfMonth;
if (!ftpClient.changeWorkingDirectory(remoteFilePath)) {
ftpClient.makeDirectory(remoteFilePath);
}
String[] split = localFilePath.split("\\.");
String path = remoteFilePath + "/" + title + "." + split[split.length - 1];
// 将中文文件名转换为服务器编码
String encodedRemoteFilePath = new String(path.getBytes("UTF-8"), "ISO-8859-1");
boolean uploadSuccess = ftpClient.storeFile(encodedRemoteFilePath, fileInputStream);
if (uploadSuccess) {
log.info("文件上传成功");
} else {
log.info("文件上传失败");
}
}
// 完成后,登出并关闭连接
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
}
}
需要注意路径问题,容易导致失败
小结
碧蓝幻想yyds