본문 바로가기

Spring Boot

[Springboot + AWS S3] AWS S3 다운로드 구현

반응형

Spring Boot 환경에서 Amazon S3에서 파일을 다운로드하려면 Java용 AWS SDK를 사용할 수 있습니다. SDK는 파일 다운로드 방법을 포함하여 아마존 S3에 액세스하기 위한 고급 API를 제공합니다.

다음은 Java용 AWS SDK를 사용하여 Amazon S3에서 파일을 다운로드하는 방법의 예입니다:

@Service
public class S3Downloader {
    private AmazonS3 s3Client;

    @Autowired
    public S3Downloader(AmazonS3 s3Client) {
        this.s3Client = s3Client;
    }

    public byte[] downloadFile(String bucketName, String fileKey) {
        S3Object s3Object = s3Client.getObject(bucketName, fileKey);
        S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            int read;
            byte[] buffer = new byte[4096];
            while ((read = objectInputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, read);
            }

            outputStream.flush();
        } catch (IOException e) {
            // handle exception
        } finally {
            try {
                objectInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                // handle exception
            }
        }

        return outputStream.toByteArray();
    }
}
반응형