Skip to content

Instantly share code, notes, and snippets.

@HiramZednem
Created November 11, 2022 15:04
Show Gist options
  • Save HiramZednem/296ec2e06266a889cb157359b03f54ff to your computer and use it in GitHub Desktop.
Save HiramZednem/296ec2e06266a889cb157359b03f54ff to your computer and use it in GitHub Desktop.
aws bucket config
package com.escuelita.demo.services;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
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.PutObjectRequest;
import com.escuelita.demo.services.interfaces.IFileService;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileServiceImpl implements IFileService {
private AmazonS3 s3client;
private String ENDPOINT_URL = "s3.us-east-2.amazonaws.com";
private String BUCKET_NAME = "upch2";
private String ACCESS_KEY = "AKIAZK7UIBZHW2CYLDGP";
private String SECRET_KEY = "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";
@Override
public String upload(MultipartFile multipartFile) {
String fileUrl = "";
try {
File file = convertMultiPartToFile(multipartFile);
String fileName = generateFileName(multipartFile);
fileUrl = "https://" + BUCKET_NAME + "." + ENDPOINT_URL + "/" + fileName;
uploadFileToS3Bucket(fileName, file);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return fileUrl;
}
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
private String generateFileName(MultipartFile multiPart) {
return multiPart.getOriginalFilename().replace(" ", "_");
}
private void uploadFileToS3Bucket(String fileName, File file) {
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, file)
.withCannedAcl(CannedAccessControlList.PublicRead);
s3client.putObject(putObjectRequest);
}
@PostConstruct
private void initializeAmazon() {
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
}
}
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.313</version>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment