0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

備忘_SpringBootでS3のファイル操作(awssdk version2.2136)

Posted at

pom.xml

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>s3</artifactId>
    <version>2.21.36</version>
</dependency>
LombokとかDB接続周りとか

Service

接続設定

環境変数にAWSのアクセスキーとシークレットキーを設定すれば実行時に読み込む。
また、AWS上で動かす場合は実行するロールのものを参照するような記述があった気がする(AWS公式見て)

@Service
public class HogeImpl implements Hoge {
    
    @Value("${aws.region}")
    private Region region;
    
    @Value("${aws.s3.bucket}")
    private String bucket;

    // 署名付きURL発行を行うために必要
    private S3Presigner presigner = S3Presigner.builder().region(region).build();

    // S3の操作をするために必要
    private S3Client s3Client =  S3Client.builder().region(region).build();

    

署名付きURLの発行(保存)

public URL genPreUrl(){
    // putするオブジェクトの情報を組み立て
    PutObjectRequest objReq = PutObjectRequest.builder()
        .bucket(bucket)
        .key("保存先となるS3Objectキー")
        .overrideConfiguration("追加で設定したいコンフィグ")//なくてもいい
        .contetType("text/plain")//なくてもいい。指定するなら必要
        .build();

    // preSignUrlの情報を組み立て
    PutObjectPresignRequest presignReq = PutObjectPresignRequest.builder()
        .signatureDuration(Duration.ofMinutes(30))//有効時間とか
        .putObjectRequest(objReq)
        .build();

    // 発行
    PresignedPutObjectRequest preSignedReq = presigner.presignPutObject(presignReq);
    URL url = preSignedReq.url();

    return url;
}

S3にあるzipファイルの解凍と格納

public void unzipUpload(){
    // S3からオブジェクトの取得
    ResponseInputStream<GetObjectResponse> zipObj = s3Client
        .getObject(GetObjectRequest.builder()
            .bucket(bucket)
            .key("取得したいObjectキー")
            .build());

    // zipのstream作成
    ZipInputStream zipInputStream = new ZipInputStream(zipObj);
    ZipEntry zipEntry;

    // zip内の全ファイルに対してループ
    try{
        while((zipEntry = zipInputStream.getNextEntry()) != null){
            ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            // 実際のバイト数を入れる変数
            int bytesRead;
            // エントリーの内容を読み込みバイト配列に書き込む
            while ((bytesRead = zipInputStream.read(buffer)) != -1){
                byteOutStream.write(buffer, 0, bytesRead);
            }
            byteOutStream.close();

            //ここから格納
            ByteArrayInputStream byteInStream = new ByteArrayInputStream(byteOutStream.toByteArray());

            // upload
            s3Client.putObject(PutObjectRequest.builder()
                .bucket(bucket)
                .key("保存するObjectキー名")
                .build()
                ,
                RequestBody.fromInputStream(byteInStream, byteInStream.available())
            );
        }
        // zipファイルの削除
        s3Client.deleteObject(DeletePbjectRequest.builder().bucket(bucket).key("削除対象").build();
    }catch ~~~~~
    ```
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?