Spring Boot S3 File Upload And Download Example ^hot^ 【ESSENTIAL ✪】
import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @RestController @RequestMapping("/api/files") public class FileController { private final S3Service s3Service; public FileController(S3Service s3Service) { this.s3Service = s3Service; } @PostMapping("/upload") public ResponseEntity upload(@RequestParam("file") MultipartFile file) { try { return ResponseEntity.ok(s3Service.uploadFile(file)); } catch (IOException e) { return ResponseEntity.internalServerError().body("Upload failed: " + e.getMessage()); } } @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. 5. Testing the Implementation Uploading a File Use or cURL to send a POST request: URL : http://localhost:8080/api/files/upload Method : POST
Store your AWS credentials and bucket details in src/main/resources/application.properties . spring boot s3 file upload and download example
The S3Service contains the logic for interacting with the bucket. It handles converting MultipartFile to a format S3 understands and fetching objects as byte arrays. import org
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; @Configuration public class S3Config { @Value("${aws.accessKeyId}") private String accessKey; @Value("${aws.secretKey}") private String secretKey; @Value("${aws.region}") private String region; @Bean public S3Client s3Client() { return S3Client.builder() .region(Region.of(region)) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create(accessKey, secretKey))) .build(); } } Use code with caution. 3. The Service Layer The S3Service contains the logic for interacting with
Create a controller to expose the endpoints. We use MultipartFile for uploads and ResponseEntity for downloads.
aws.accessKeyId=YOUR_ACCESS_KEY aws.secretKey=YOUR_SECRET_KEY aws.region=us-east-1 aws.s3.bucketName=my-springboot-bucket Use code with caution.