Java Techie Repack — Spring Boot With Amazon S3 File Upload And Download Example S3 Bucket
Store your credentials and bucket details in src/main/resources/application.properties . properties
Integrating Amazon S3 with Spring Boot is a standard requirement for modern cloud-native applications. This guide provides a complete walkthrough for implementing file upload and download functionality using the AWS SDK for Java. Prerequisites An active AWS Account. An S3 Bucket created in your preferred region. AWS Access Key and Secret Key with S3 permissions. Java 17 or higher. Maven or Gradle. Step 1: Add Dependencies Prerequisites An active AWS Account
@Service public class S3Service { @Value("${aws.s3.bucket.name}") private String bucketName; @Autowired private S3Client s3Client; public String uploadFile(MultipartFile file) { String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); try { PutObjectRequest putObjectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(fileName) .build(); s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); return "File uploaded successfully: " + fileName; } catch (IOException e) { throw new RuntimeException("Upload failed", e); } } public byte[] downloadFile(String fileName) { GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(bucketName) .key(fileName) .build(); ResponseInputStream response = s3Client.getObject(getObjectRequest); try { return response.readAllBytes(); } catch (IOException e) { throw new RuntimeException("Download failed", e); } } } Use code with caution. Step 5: Create the REST Controller Java 17 or higher