import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ftp")
public class FtpDownloadController {
@RequestMapping("/download/{remoteFile}")
public ResponseEntity<Resource> downloadFile(@PathVariable String remoteFile) {
String server = "your_server_address";
int port = 21;
String username = "your_username";
String password = "your_password";
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
byte[] fileContent = inputStream.readAllBytes();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + remoteFile);
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new ByteArrayResource(fileContent));
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(500).body(null);
}
}
}