Last active
October 18, 2020 05:00
ImageService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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