2
0

More than 3 years have passed since last update.

【備忘】S3からのダウンロード、S3へのアップロード

Posted at

1.S3からのファイルダウンロード
今回は、バケットの対象パス下のファイルを全てダウンロードする場合を記述しました。

  AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion("リージョン名").build();

  // S3上バケット下のファイル一覧を取得
  ObjectListing objListing = s3Client.listObjects("バケット名");
  List<S3ObjectSummary> objList = objListing.getObjectSummaries();

  try {
    // S3上のファイル分処理する
    for (S3ObjectSummary obj : objList) {
      // objListにはバケット下全てのフォルダ、ファイル情報があるため対象パスで絞り込む必要がある
      // 対象パスを含んでいないか、または、サイズが0であればダウンロードしない
      if (!StringUtils.contains(obj.getKey(), "対象パス") || obj.getSize() == 0) {
        continue;
      }

      // 以下ダウンロード処理
      // obj.getKey()は"対象パス/ファイル名"となっている
      GetObjectRequest request = new GetObjectRequest("バケット名", obj.getKey());
      // ファイル名だけにする
      String fileName = obj.getKey().replace("対象パス", "");
      // ダウンロード先のファイルを生成
      File file = new File(fileName);
      if (s3Client.getObject(request, file) == null) {
        // ダウンロード失敗
      }
    }
  } catch (IOException e) {
    throw e;
  }

2.S3へのアップロード
ファイルをバケット下の対象パスへアップロードする場合

  try {
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion("リージョン名").build();

    File file = new File("アップロード対象ファイル名");
    PutObjectRequest request = new PutObjectRequest("バケット名", "対象パス" + file.getName(), file);
    request.setCannedAcl(CannedAccessControlList.PublicRead);
    s3Client.putObject(request);
  } catch (Exception e) {
    throw e;
  }

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0