直接调用downloadFiles方法即可
package com.demo.utils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FtpFileDownloader {
@PostMapping("/downloadFtpFiles")
public ResponseEntity<?> downloadFtpFiles(@RequestParam("filePaths") List<String> filePaths) throws IOException {
return null;
}
public void downloadFiles(List<String> filePaths, HttpServletResponse response) throws IOException {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.login("your_username", "your_password");
if (filePaths.size() > 1) {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"files.zip\"");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
for (String filePath : filePaths) {
FTPFile ftpFile = ftpClient.listFiles(filePath)[0];
if (ftpFile.isFile()) {
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
if (inputStream == null) {
continue;
}
ZipEntry zipEntry = new ZipEntry(getFileNameFromPath(filePath));
zos.putNextEntry(zipEntry);
IOUtils.copy(inputStream, zos);
zos.closeEntry();
inputStream.close();
ftpClient.completePendingCommand();
}
}
zos.finish();
zos.close();
} else if (filePaths.size() == 1) {
String singleFilePath = filePaths.get(0);
FTPFile ftpFile = ftpClient.listFiles(singleFilePath)[0];
if (ftpFile.isFile()) {
response.setContentType(getContentTypeFromFileName(singleFilePath));
response.setHeader("Content-Disposition", "attachment; filename=\"" + getFileNameFromPath(singleFilePath) + "\"");
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = ftpClient.retrieveFileStream(singleFilePath);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.flush();
}
}
} catch (IOException e) {
throw e;
} finally {
ftpClient.logout();
ftpClient.disconnect();
}
}
private String getFileNameFromPath(String path) {
return path.substring(path.lastIndexOf("/") + 1);
}
private String getContentTypeFromFileName(String fileName) {
return fileName.endsWith(".pdf") ? "application/pdf" : "application/octet-stream";
}
}