Skip to content

Instantly share code, notes, and snippets.

@mmafrar
Created March 24, 2021 15:49
Show Gist options
  • Save mmafrar/26f545833021ef01b0ce9709a8cc2331 to your computer and use it in GitHub Desktop.
Save mmafrar/26f545833021ef01b0ce9709a8cc2331 to your computer and use it in GitHub Desktop.
Working with Amazon S3 presigned URLs in Spring Boot
package com.example.demo;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
@Service
public class FileServiceNew {
private static final Logger LOG = LoggerFactory.getLogger(FileServiceNew.class);
@Autowired
private AmazonS3 amazonS3;
@Value("${s3.bucket.name}")
private String s3BucketName;
private String generateUrl(String fileName, HttpMethod httpMethod) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, 1); // Generated URL will be valid for 24 hours
return amazonS3.generatePresignedUrl(s3BucketName, fileName, calendar.getTime(), httpMethod).toString();
}
@Async
public String findByName(String fileName) {
if (!amazonS3.doesObjectExist(s3BucketName, fileName))
return "File does not exist";
LOG.info("Generating signed URL for file name {}", fileName);
return generateUrl(fileName, HttpMethod.GET);
}
@Async
public String save(String extension) {
String fileName = UUID.randomUUID().toString() + extension;
return generateUrl(fileName, HttpMethod.PUT);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment