たなちの備忘録

自分の知識をストックしていくためのブログ

【AWS】S3にオブジェクトをアップロードする

スポンサーリンク

JavaでS3にファイルをアップロードする処理を書くことがあったので、残してみます。

docs.aws.amazon.com

Apache Maven での SDK の使用

Mavenを使っている場合は下記をpom.xmlに追加すれば使えるようになります。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
</dependency>

Apache Maven での SDK の使用 - AWS SDK for Java

AWSクライアントに認証情報を指定

AmazonS3Client のインスタンスを作成します。

AWSCredentials インターフェイスを提供するクラス (BasicAWSCredentials など) をインスタンス化し、接続に使用する AWS アクセスキーおよびシークレットキーを指定します。

AWS 認証情報の使用 - AWS SDK for Java

アップロード

putObjectメソッドの引数は、バケット名、キー、ファイル。 これで指定したバケット以下にファイルがアップロードされます。

public PutObjectResult putObject(String bucketName,
                                 String key,
                                 File file)
                          throws SdkClientException,
                                 AmazonServiceException

サンプルコード

/**
 * S3へファイルをアップロード
 *
 * @param file ファイル
 * @throws IOException
 */
public void uploadS3(File file) throws IOException {

    String bucketName = "*** Provide bucket name ***";   // バケット名
    String keyName = "*** Provide key ***";  // S3上のファイル名

    String accessKey = "xxxxx";  // アクセスキー
    String secretKey = "xxxxx";  // シークレットキー

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonS3 s3client = new AmazonS3Client(credentials);

    try {

        System.out.println("Uploading a new object to S3 from a file\n");
        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());
    }
}