Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
awsdocs
GitHub Repository: awsdocs/amazon-s3-developer-guide
Path: blob/master/code_examples/java_examples/S3Examples/UploadObject.java
4084 views
1
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)
3
4
import java.io.File;
5
import java.io.IOException;
6
7
import com.amazonaws.AmazonServiceException;
8
import com.amazonaws.SdkClientException;
9
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
10
import com.amazonaws.services.s3.AmazonS3;
11
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
12
import com.amazonaws.services.s3.model.ObjectMetadata;
13
import com.amazonaws.services.s3.model.PutObjectRequest;
14
15
public class UploadObject {
16
17
public static void main(String[] args) throws IOException {
18
String clientRegion = "*** Client region ***";
19
String bucketName = "*** Bucket name ***";
20
String stringObjKeyName = "*** String object key name ***";
21
String fileObjKeyName = "*** File object key name ***";
22
String fileName = "*** Path to file to upload ***";
23
24
try {
25
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
26
.withRegion(clientRegion)
27
.withCredentials(new ProfileCredentialsProvider())
28
.build();
29
30
// Upload a text string as a new object.
31
s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");
32
33
// Upload a file as a new object with ContentType and title specified.
34
PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));
35
ObjectMetadata metadata = new ObjectMetadata();
36
metadata.setContentType("text/plain");
37
metadata.addUserMetadata("x-amz-meta-title", "someTitle");
38
request.setMetadata(metadata);
39
s3Client.putObject(request);
40
}
41
catch(AmazonServiceException e) {
42
// The call was transmitted successfully, but Amazon S3 couldn't process
43
// it, so it returned an error response.
44
e.printStackTrace();
45
}
46
catch(SdkClientException e) {
47
// Amazon S3 couldn't be contacted for a response, or the client
48
// couldn't parse the response from Amazon S3.
49
e.printStackTrace();
50
}
51
}
52
}
53