· 7 years ago · Jul 25, 2018, 06:32 PM
1private void uploadFileAWS(ServletContext context, InputStream input, Long contentLength, String key) throws Exception{
2
3 AWSCredentials credentials = null;
4 try {
5 String accessKey = AWSUtils.getAccessKey(context);
6 String secretKey = AWSUtils.getSecretKey(context);
7
8 System.out.println(String.format("%s: %s", "Access key", accessKey));
9 System.out.println(String.format("%s: %s", "Secret key", secretKey));
10 credentials = new BasicAWSCredentials(accessKey, secretKey);
11 } catch (Exception e) {
12 throw new AmazonClientException(
13 "Cannot load the credentials from the credential profiles file. " +
14 "Please make sure that your credentials file is at the correct " +
15 "location (~/.aws/credentials), and is in valid format.",
16 e);
17 }
18
19
20 AmazonS3 s3 = AmazonS3ClientBuilder.standard()
21 .withCredentials(new AWSStaticCredentialsProvider(credentials))
22 .withRegion(Regions.US_WEST_1)
23 .build();
24
25 String bucketName = "test-images-facnog";
26
27 System.out.println("===========================================");
28 System.out.println("Getting Started with Amazon S3");
29 System.out.println("===========================================\n");
30
31 try {
32
33 System.out.println("Uploading a new object to S3 from a stream\n");
34 ObjectMetadata x = new ObjectMetadata();
35 x.setContentLength(contentLength);
36 s3.putObject(new PutObjectRequest(bucketName, key, input, x));
37
38 } catch (AmazonServiceException ase) {
39 System.out.println("Caught an AmazonServiceException, which means your request made it "
40 + "to Amazon S3, but was rejected with an error response for some reason.");
41 System.out.println("Error Message: " + ase.getMessage());
42 System.out.println("HTTP Status Code: " + ase.getStatusCode());
43 System.out.println("AWS Error Code: " + ase.getErrorCode());
44 System.out.println("Error Type: " + ase.getErrorType());
45 System.out.println("Request ID: " + ase.getRequestId());
46 } catch (AmazonClientException ace) {
47 System.out.println("Caught an AmazonClientException, which means the client encountered "
48 + "a serious internal problem while trying to communicate with S3, "
49 + "such as not being able to access the network.");
50 System.out.println("Error Message: " + ace.getMessage());
51 }
52 }