· 7 years ago · Mar 24, 2018, 06:20 PM
1@Service
2public class AmazonS3Service {
3 private AmazonS3 s3client;
4
5 @Value("${amazonProperties.endpointUrl}")
6 private String endpointUrl;
7
8 @Value("${amazonProperties.bucketName}")
9 private String bucketName;
10
11 @Value("${amazonProperties.accessKey}")
12 private String accessKey;
13
14 @Value("${amazonProperties.secretKey}")
15 private String secretKey;
16
17 @Autowired
18 CatererRepository catererRepository;
19
20 @Autowired
21 NotificationGenerateDeliveryOrders notificationGenerateDeliveryOrders;
22
23 @PostConstruct
24 private void initializeAmazon() {
25 AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
26 this.s3client = new AmazonS3Client(credentials);
27 }
28
29 private File convertMultiPartToFile(MultipartFile file) throws IOException {
30 File convFile = new File(file.getOriginalFilename());
31 FileOutputStream fos = new FileOutputStream(convFile);
32 fos.write(file.getBytes());
33 fos.close();
34 return convFile;
35 }
36
37 private String generateFileName(MultipartFile multiPart) {
38 return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
39
40 }
41
42 private void uploadFileTos3bucket(String fileName, File file) {
43 s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
44 .withCannedAcl(CannedAccessControlList.PublicRead));
45 }
46
47 public String uploadFile(MultipartFile multipartFile) {
48
49 String fileUrl = "";
50 try {
51 File file = convertMultiPartToFile(multipartFile);
52 String fileName = generateFileName(multipartFile);
53 fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
54 uploadFileTos3bucket(fileName, file);
55 file.delete();
56 } catch (Exception e) {
57 e.printStackTrace();
58 }
59 return fileUrl;
60 }
61
62 public String deleteFileFromS3Bucket(String fileUrl) {
63 String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
64 s3client.deleteObject(new DeleteObjectRequest(bucketName + "/", fileName));
65 return "Successfully deleted";
66 }
67}