Amazon Simple Storage Service
开发人员指南 (API Version 2006-03-01)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。请点击 Amazon AWS 入门,可查看中国地区的具体差异

使用 AWS SDK for Java 上传对象

以下任务将引导您使用 Java 类来上传文件。API 提供了 方法的多个变体 (称为重载putObject),使您可以轻松地上传数据。

上传对象

1

创建 AmazonS3Client 的实例。

2

根据您是从文件还是从流上传数据,执行任意一个 AmazonS3Client.putObject 重载。

以下 Java 代码示例演示了上述任务。

Copy
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); s3client.putObject(new PutObjectRequest(bucketName, keyName, file));

以下 Java 代码示例将文件上传到 Amazon S3 存储桶。有关如何创建和测试有效示例的说明,请参阅 测试 Java 代码示例

Copy
import java.io.File; import java.io.IOException; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.PutObjectRequest; public class UploadObjectSingleOperation { private static String bucketName = "*** Provide bucket name ***"; private static String keyName = "*** Provide key ***"; private static String uploadFileName = "*** Provide file name ***"; public static void main(String[] args) throws IOException { AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider()); try { System.out.println("Uploading a new object to S3 from a file\n"); File file = new File(uploadFileName); s3client.putObject(new PutObjectRequest( bucketName, keyName, file)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }