在附件管理模块中增加FTP上传和预览支持,核心需要完成FTP连接管理、文件上传逻辑适配、预览接口适配三个部分的工作,下面以Java技术栈为例详细讲解实现过程。

FTP连接配置与工具类封装
首先需要封装FTP操作的基础工具类,处理连接创建、关闭、文件传输等通用逻辑,避免重复代码。这里使用Apache Commons Net提供的FTPClient实现FTP操作。
先在项目的pom.xml中引入依赖:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
接下来封装FTP工具类,包含连接、上传、下载、关闭连接等核心方法:
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
import java.io.InputStream;
public class FtpUtil {
private String host;
private int port;
private String username;
private String password;
private FTPClient ftpClient;
public FtpUtil(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.ftpClient = new FTPClient();
}
// 建立FTP连接
public boolean connect() {
try {
ftpClient.connect(host, port);
ftpClient.login(username, password);
// 设置文件传输类型为二进制,避免文件损坏
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 开启被动模式,适配大部分网络环境
ftpClient.enterLocalPassiveMode();
int replyCode = ftpClient.getReplyCode();
return FTPReply.isPositiveCompletion(replyCode);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
// 上传文件到指定FTP路径
public boolean uploadFile(String remotePath, String fileName, InputStream inputStream) {
try {
// 切换到目标目录,不存在则创建
String[] pathSegments = remotePath.split("/");
String currentPath = "/";
for (String segment : pathSegments) {
if (segment.isEmpty()) {
continue;
}
currentPath += segment + "/";
if (!ftpClient.changeWorkingDirectory(currentPath)) {
ftpClient.makeDirectory(currentPath);
ftpClient.changeWorkingDirectory(currentPath);
}
}
// 上传文件
return ftpClient.storeFile(fileName, inputStream);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
// 获取文件输入流用于预览
public InputStream getFileInputStream(String remotePath, String fileName) {
try {
ftpClient.changeWorkingDirectory(remotePath);
return ftpClient.retrieveFileStream(fileName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 关闭连接
public void close() {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
附件管理模块上传逻辑适配
原有的附件上传逻辑通常只处理本地存储,需要修改上传流程,增加FTP上传的开关和对应逻辑。首先在配置文件中增加FTP相关配置项:
# FTP配置 ftp.enable=true ftp.host=192.168.0.1 ftp.port=21 ftp.username=ftp_user ftp.password=ftp_pass ftp.base_path=/attachment
修改附件上传的服务层代码,根据配置决定是否上传到FTP:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Service
public class AttachmentService {
@Value("${ftp.enable}")
private boolean ftpEnable;
@Value("${ftp.host}")
private String ftpHost;
@Value("${ftp.port}")
private int ftpPort;
@Value("${ftp.username}")
private String ftpUsername;
@Value("${ftp.password}")
private String ftpPassword;
@Value("${ftp.base_path}")
private String ftpBasePath;
public String uploadAttachment(MultipartFile file) {
// 生成唯一文件名,避免重复
String originalFilename = file.getOriginalFilename();
String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString().replace("-", "") + fileSuffix;
// 按日期生成存储路径,方便管理
String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
String remotePath = ftpBasePath + "/" + datePath;
if (ftpEnable) {
// FTP上传逻辑
FtpUtil ftpUtil = new FtpUtil(ftpHost, ftpPort, ftpUsername, ftpPassword);
if (ftpUtil.connect()) {
try {
boolean uploadSuccess = ftpUtil.uploadFile(remotePath, fileName, file.getInputStream());
if (uploadSuccess) {
// 返回FTP路径,用于后续预览和下载
return "ftp://" + ftpHost + remotePath + "/" + fileName;
}
} finally {
ftpUtil.close();
}
}
throw new RuntimeException("FTP上传失败");
} else {
// 原有本地上传逻辑,这里省略具体实现
return "本地存储路径";
}
}
}
附件预览功能适配
附件预览需要根据存储类型返回不同的资源访问方式,如果是FTP存储的文件,不能直接通过本地路径访问,需要新增预览接口,从FTP读取文件流返回给前端。
新增预览接口的代码实现:
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
@RestController
public class AttachmentPreviewController {
@Value("${ftp.host}")
private String ftpHost;
@Value("${ftp.port}")
private int ftpPort;
@Value("${ftp.username}")
private String ftpUsername;
@Value("${ftp.password}")
private String ftpPassword;
@GetMapping("/attachment/preview")
public ResponseEntity<byte[]> previewAttachment(@RequestParam String filePath) {
// 解析FTP路径,提取远程路径和文件名
// 假设filePath格式为ftp://host/base_path/date/fileName
String pathWithoutProtocol = filePath.replace("ftp://" + ftpHost, "");
int lastSlashIndex = pathWithoutProtocol.lastIndexOf("/");
String remotePath = pathWithoutProtocol.substring(0, lastSlashIndex);
String fileName = pathWithoutProtocol.substring(lastSlashIndex + 1);
FtpUtil ftpUtil = new FtpUtil(ftpHost, ftpPort, ftpUsername, ftpPassword);
if (ftpUtil.connect()) {
try {
InputStream inputStream = ftpUtil.getFileInputStream(remotePath, fileName);
if (inputStream != null) {
byte[] fileBytes = inputStream.readAllBytes();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("inline", fileName);
return ResponseEntity.ok()
.headers(headers)
.body(fileBytes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ftpUtil.close();
}
}
return ResponseEntity.notFound().build();
}
}
注意事项
- FTP连接建议使用连接池管理,避免频繁创建和销毁连接带来的性能损耗。
- 大文件上传时需要考虑超时配置,避免上传过程中连接中断,可以通过
ftpClient.setDefaultTimeout(30000)设置超时时间。 - 预览接口需要根据文件类型设置正确的
Content-Type,比如图片类型设置为image/jpeg,pdf类型设置为application/pdf,提升前端预览体验。 - 生产环境中FTP密码等敏感配置建议加密存储,不要明文写在配置文件中。
FTP上传附件管理文件预览FTP_client修改时间:2026-07-07 22:36:38