How To Download //top\\ File From S3 Bucket Using Spring Boot May 2026
(Access Key and Secret Key) with s3:GetObject permissions. Java 17+ and Maven or Gradle . 1. Add Dependencies
@Service public class S3Service { private final S3Client s3Client; @Value("${aws.s3.bucket-name}") private String bucketName; public S3Service(S3Client s3Client) { this.s3Client = s3Client; } public byte[] downloadFile(String key) { GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(bucketName) .key(key) .build(); return s3Client.getObjectAsBytes(getObjectRequest).asByteArray(); } } Use code with caution. 4. Build the REST Controller how to download file from s3 bucket using spring boot
@RestController @RequestMapping("/api/files") public class FileController { private final S3Service s3Service; public FileController(S3Service s3Service) { this.s3Service = s3Service; } @GetMapping("/download/{fileName}") public ResponseEntity download(@PathVariable String fileName) { byte[] data = s3Service.downloadFile(fileName); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(data); } } Use code with caution. Best Practices for S3 Downloads (Access Key and Secret Key) with s3:GetObject permissions