· 7 years ago · Oct 20, 2018, 09:58 AM
1import com.amazonaws.auth.AWSCredentials;
2import com.amazonaws.auth.AWSStaticCredentialsProvider;
3import com.amazonaws.auth.BasicAWSCredentials;
4import com.amazonaws.services.s3.AmazonS3;
5import com.amazonaws.services.s3.AmazonS3Client;
6import com.amazonaws.services.s3.AmazonS3ClientBuilder;
7import com.amazonaws.services.s3.model.CannedAccessControlList;
8import com.amazonaws.services.s3.model.PutObjectRequest;
9import org.springframework.beans.factory.annotation.Value;
10import org.springframework.stereotype.Service;
11import org.springframework.web.multipart.MultipartFile;
12
13import javax.annotation.PostConstruct;
14import java.io.File;
15import java.io.FileOutputStream;
16import java.io.IOException;
17import java.util.Date;
18
19@Service
20public class AmazonClient {
21
22 private AmazonS3 s3client;
23
24 @Value("${amazonProperties.endpointUrl}")
25 private String endpointUrl;
26 @Value("${amazonProperties.bucketName}")
27 private String bucketName;
28 @Value("${amazonProperties.accessKey}")
29 private String accessKey;
30 @Value("${amazonProperties.secretKey}")
31 private String secretKey;
32 @Value("${amazonProperties.region}")
33 private String region;
34
35 @PostConstruct
36 private void initializeAmazon() {
37// AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
38// this.s3client = new AmazonS3Client(credentials);
39 BasicAWSCredentials creds = new BasicAWSCredentials(this.accessKey, this.secretKey);
40 s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).build();
41 }
42
43 public String upload(MultipartFile multipartFile) {
44 String fileUrl = "";
45 try {
46 File file = convertMultiPartToFile(multipartFile);
47 String fileName = generateFileName(multipartFile);
48 fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
49 uploadFileTos3bucket(fileName, file);
50 file.delete();
51 } catch (Exception e) {
52 e.printStackTrace();
53 }
54 return fileUrl;
55 }
56
57 //
58 private File convertMultiPartToFile(MultipartFile file) throws IOException {
59 File convFile = new File(file.getOriginalFilename());
60 FileOutputStream fos = new FileOutputStream(convFile);
61 fos.write(file.getBytes());
62 fos.close();
63 return convFile;
64 }
65 //generate unique name to the uploadfile
66 private String generateFileName(MultipartFile multiPart) {
67 return new Date().getTime() + "-" + multiPart.getOriginalFilename().replace(" ", "_");
68 }
69
70 //upload files to s3
71 private void uploadFileTos3bucket(String fileName, File file) {
72 s3client.putObject(new PutObjectRequest(bucketName, fileName, file)
73 .withCannedAcl(CannedAccessControlList.PublicRead));
74 }
75}