Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

使用 AWS SDK for Java 上传对象

以下示例将创建两个对象。第一个对象将一个文本字符串作为数据,第二对象是一个文件。该示例通过在对 AmazonS3Client.putObject() 的调用中直接指定存储桶名称、对象键和文本数据来创建第一个对象。该示例通过使用指定存储桶、对象键和文件路径的 PutObjectRequest 来创建第二个对象。PutObjectRequest 还指定 ContentType 标头和标题元数据。

有关创建和测试有效示例的说明,请参阅测试 Amazon S3 Java 代码示例

import java.io.File; import java.io.IOException; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; public class UploadObject { public static void main(String[] args) throws IOException { String clientRegion = "*** Client region ***"; String bucketName = "*** Bucket name ***"; String stringObjKeyName = "*** String object key name ***"; String fileObjKeyName = "*** File object key name ***"; String fileName = "*** Path to file to upload ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(clientRegion) .withCredentials(new ProfileCredentialsProvider()) .build(); // Upload a text string as a new object. s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object"); // Upload a file as a new object with ContentType and title specified. PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName)); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("plain/text"); metadata.addUserMetadata("x-amz-meta-title", "someTitle"); request.setMetadata(metadata); s3Client.putObject(request); } catch(AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch(SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }