Skip to content

Instantly share code, notes, and snippets.

@h-hub
Last active October 18, 2020 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h-hub/73e7a0932bf9e452e298df1b8be293d8 to your computer and use it in GitHub Desktop.
Save h-hub/73e7a0932bf9e452e298df1b8be293d8 to your computer and use it in GitHub Desktop.
ImageService.java
public String uploadImage(MultipartFile image, String bucketName) {
File imageFile;
try {
imageFile = convertMultiPartToFile(image);
} catch (IOException e) {
throw new FileUploadException("Unable to convert input stream to file.");
}
BufferedImage bimg = null;
try {
bimg = ImageIO.read(imageFile);
} catch (IOException e) {
throw new FileUploadException("Unable to read image.");
}
AmazonS3 s3client = AmazonS3ClientBuilder.standard().withRegion("ap-southeast-1").build();
TransferManager xfer_mgr = TransferManagerBuilder.standard().withS3Client(s3client).build();
String fileName = generateFileName(image);
try {
Upload xfer = xfer_mgr.upload(new PutObjectRequest(bucketName, fileName, imageFile)
.withCannedAcl(CannedAccessControlList.PublicRead));
xfer.waitForCompletion();
} catch (AmazonServiceException | InterruptedException e) {
throw new FileUploadException("AWS Error or Upload was interrupted");
}
xfer_mgr.shutdownNow();
return "https://"+bucketName+".s3-ap-southeast-1.amazonaws.com/"+fileName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment