How to Download Large Files from Amazon S3 Bucket in Spring Boot

Here is a example code to download files from Amazon S3 buckets in Spring Boot.

Follow the steps below to complete this example:

Adding Dependency

To upload files to S3, you will need to add the AWS Java SDK For Amazon S3 dependency to your application. Here is the Maven repository for Amazon S3 SDK for Java.

Gradle Dependency

Add the following dependency to the build.gradle file:


implementation group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.12.158'
Maven Dependency

Add the following dependency to the pom.xml file:



Adding Configurations

First, add the following credentials to your resources/application.properties configuration file:


server.port=8080

aws.access-key = your aws access key here
aws.access-secret-key = your aws secret key here
aws.region = us-east-1

Creating Configuration Classes

Create a configuration Java class for the AmazonS3 Client:

spring-boot-s3-sample/src/main/java/com/s3/sample/demo/config/AwsConfig.java

package com.s3.sample.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

@Configuration
public class AwsConfig {

	private String awsAccessKey;
	private String awsAccessSecretKey;
	private String awsRegion;

	public AwsConfig(@Value(value = "${aws.access-key}") String awsAccessKey,
			@Value(value = "${aws.access-secret-key}") String awsAccessSecretKey,
			@Value(value = "${aws.region}") String awsRegion) {
		this.awsAccessKey = awsAccessKey;
		this.awsAccessSecretKey = awsAccessSecretKey;
		this.awsRegion = awsRegion;
	}

	public AWSStaticCredentialsProvider getAwsCredentialsProvider() {
		BasicAWSCredentials awsCred = new BasicAWSCredentials(this.awsAccessKey, this.awsAccessSecretKey);
		return new AWSStaticCredentialsProvider(awsCred);
	}

	@Bean
	public AmazonS3 getAmazonS3Client() {
		return AmazonS3ClientBuilder.standard().withRegion(this.awsRegion).withCredentials(getAwsCredentialsProvider())
				.build();
	}
}

Next, create AsyncConfig class and configure the TaskExecutor. It is recommended that you explicitly configure the TaskExecutor if the file to be downloaded is large and will take more than a minute to download. Here is the complete code for configuring the TaskExecutor with a request timeout of 3600000 milliseconds (60 minutes):

spring-boot-s3-sample/src/main/java/com/s3/sample/demo/config/AsyncConfig.java

package com.s3.sample.demo.config;

import java.util.concurrent.Callable;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
import org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfig implements AsyncConfigurer {

	@Override
	@Bean(name = "taskExecutor")
	public AsyncTaskExecutor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(10);
		executor.setMaxPoolSize(15);
		executor.setQueueCapacity(50);
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}

	@Bean
	public WebMvcConfigurer webMvcConfigurerConfigurer(AsyncTaskExecutor taskExecutor,
			CallableProcessingInterceptor callableProcessingInterceptor) {
		return new WebMvcConfigurer() {
			@Override
			public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
				configurer.setDefaultTimeout(3600000).setTaskExecutor(taskExecutor);
				configurer.registerCallableInterceptors(callableProcessingInterceptor);
				WebMvcConfigurer.super.configureAsyncSupport(configurer);
			}
		};
	}

	@Bean
	public CallableProcessingInterceptor callableProcessingInterceptor() {
		return new TimeoutCallableProcessingInterceptor() {
			@Override
			public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception {
				return super.handleTimeout(request, task);
			}
		};
	}
}

Creating Service

Create a service class with a method to download a file from Amazon S3:

spring-boot-s3-sample/src/main/java/com/s3/sample/demo/service/S3DownloadServiceExample.java

package com.s3.sample.demo.service;

import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

@Service
public class S3DownloadServiceExample {

	private String bucketName = "my-test-bucket";

	private String s3FolderName = "/myfolder/images/";

	@Autowired
	private AmazonS3 s3Client;

	public StreamingResponseBody downloadFileFromS3(HttpServletResponse response, String fileId) {
		// get filename from database by fileId
		String filename = "admission.pdf";
		// file location in S3
		String fileLocationKey = s3FolderName + filename;

		return outputStream -> {
			S3Object s3Object = null;
			InputStream inputStream = null;

			/* Retrieve file as object from S3 */
			s3Object = s3Client.getObject(new GetObjectRequest(bucketName, fileLocationKey));

			inputStream = s3Object.getObjectContent();

			long fileLength = s3Object.getObjectMetadata().getContentLength();

			response.setContentLength((int) fileLength);
			response.setHeader("Content-Disposition", "attachment; filename=" + filename);

			int BUFFER_SIZE = 1024;
			int bytesRead;
			byte[] buffer = new byte[BUFFER_SIZE];

			// Writing to output stream
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
			}

			// Closing all streams
			if (inputStream != null) {
				inputStream.close();
			}
			if (s3Object != null) {
				s3Object.close();
			}
			if (response != null) {
				response.getOutputStream().close();
			}
		};

	}

}

Creating Web Controller

Create a controller with a REST API endpoint that allows to download a file from S3:

spring-boot-s3-sample/src/main/java/com/s3/sample/demo/controller/AmazonS3DownloadExampleController.java

package com.s3.sample.demo.controller;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import com.s3.sample.demo.service.S3DownloadServiceExample;

@RestController
@RequestMapping(value = "/api/files")
public class AmazonS3DownloadExampleController {

	@Autowired
	private S3DownloadServiceExample s3DownloadServiceExample;

	@GetMapping(value = "/{fileId}/download")
	public ResponseEntity<StreamingResponseBody> downloadFile(HttpServletResponse response,
			@PathVariable(name = "fileId", required = true) String fileId) {

		return ResponseEntity.ok(s3DownloadServiceExample.downloadFileFromS3(response, fileId));
	}

}

The code is complete. You can run and test it now.