REST API to upload base64 image String to AWS S3 Bucket
In this article we are going to see how to upload base64 image to AWS s3 bucket.
Table of Contents
Dependency
<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.1030</version> </dependency>
Base64 String to Image File
public static File getImageFromBase64(String base64String, String fileName) { String[] strings = base64String.split(","); String extension; switch (strings[0]) { // check image's extension case "data:image/jpeg;base64": extension = "jpeg"; break; case "data:image/png;base64": extension = "png"; break; default: // should write cases for more images types extension = "jpg"; break; } // convert base64 string to binary data byte[] data = DatatypeConverter.parseBase64Binary(strings[1]); File file = new File(fileName + extension); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) { outputStream.write(data); } catch (IOException e) { e.printStackTrace(); } return file; }
Spring Boot REST Controller (StorageController)
@RestController @RequestMapping("/storage") public class StorageController { @Autowired StorageService storageService; @PostMapping("/upload") public String upload(@RequestBody UploadBean uploadBean) { storageService.store(uploadBean); return "Upload Success!"; } }
UploadBean
public class UploadBean { private String image; private String name; public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
StorageService
import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.mirthbees.stepsrank.bean.ProfileUploadBean; import com.mirthbees.stepsrank.utility.Utils; @Service public class StorageService { Logger log = LoggerFactory.getLogger(this.getClass().getName()); // @Autowired private AmazonS3 s3client; private static String defaultRegion = "ap-south-1"; @Value("${amazonProperties.endpointUrl.mumbai}") private String defaultEndpointUrl; @Value("${amazonProperties.bucketName}") private String bucketName; @Value("${amazonProperties.accessKey}") private String accessKey; @Value("${amazonProperties.secretKey}") private String secretKey; public String store(ProfileUploadBean profileUploadBean) { String fileName = profileUploadBean.getName(); String fileUrl = ""; try { File file = Utils.getImageFromBase64(profileUploadBean.getImage(), fileName); buildAmazonS3Client(defaultRegion, defaultEndpointUrl); fileUrl = defaultEndpointUrl + "/" + bucketName + "/" + fileName; uploadFileTos3bucket(fileName, file); file.delete(); log.info("File uploaded to S3 successfully"); } catch (Exception e) { log.error("Error while uploadeding the file to S3" + e); // fileUrl = "exception: "+e.getMessage(); throw e; } return fileUrl; } private void uploadFileTos3bucket(String fileName, File file) { ObjectMetadata metadata = new ObjectMetadata(); metadata.setCacheControl("51635000"); metadata.setExpirationTime(Utils.getTwentyYearsFromNow()); s3client.putObject(new PutObjectRequest(bucketName, fileName, file) .withCannedAcl(CannedAccessControlList.PublicRead).withMetadata(metadata)); } void buildAmazonS3Client(String defaultRegion, String endpoint) { AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey); AmazonS3ClientBuilder amazons3ClientBuilder = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, defaultRegion)); this.s3client = amazons3ClientBuilder.build(); } }
AWS Properties
amazonProperties.endpointUrl.mumbai=https://s3.ap-south-1.amazonaws.com amazonProperties.accessKey=YOUR_ACCESS_KEY amazonProperties.secretKey=YOUR_SECRET_KEY amazonProperties.bucketName=YOUR_BUCKET_NAME
getTwentyYearsFromNow (Utility for AWS Bucket File Cache)
public static Date getTwentyYearsFromNow() { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.YEAR, 20); Date newDate = c.getTime(); return newDate; }
Testing & Output
REST API:
http://localhost:8712/storage/upload
Request Body:
{"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAC0CAIAAACyr5FlAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAP+lSURBVHhehP11kGTnteaNtqXG4kosSGZmZi5mhmQsZmZmpqws6upusWQxmRlkkWXZktlnfM6Zb2YivrgwN2Li3j/uXbtS1vHMxBdXseL1m7t2ZrX7/eWznmdT30p4suP+9FNf6kkg9SSYeRxEHQfwW37WXp/j9eOe68my3ea8Cx864cs8Cz44Cz59Grh96rtz6rtUVORK5CYII=","name": "Ngdeveloper.png"}