今回は、ファイルをAWS S3に格納する方法についてみていきたいと思います。
BuildツールはMavenを使います。
AWS S3関連のdependency追加
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-context</artifactId>
<version>2.3.0-RC2</version>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-autoconfigure</artifactId>
<version>2.3.0-RC2</version>
</dependency>
AWS S3を使用するためには上記のようにpom.xmlにdependencyを追加する必要があります。
アップロードのサンプル
package com.anveloper.youtubeclone.service;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import java.io.IOException;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
@RequiredArgsConstructor
@Service
public class S3Service implements FileService {
private final AmazonS3Client awsS3Client;
public static final String BUCKET_NAME = "sample-bucket";
@Override
public String uploadFile(MultipartFile file) {
var filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());
var key = UUID.randomUUID().toString() + "." + filenameExtension;
var metadata = new ObjectMetadata();
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());
try {
awsS3Client.putObject(BUCKET_NAME, key, file.getInputStream(), metadata);
} catch (IOException ex) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "ファイルアップロード失敗");
}
awsS3Client.setObjectAcl(BUCKET_NAME, key, CannedAccessControlList.PublicRead);
return awsS3Client.getResourceUrl(BUCKET_NAME, key);
}
}
- AmazonS3Client:AWS S3を使用するためのクラスとなり、AutowiredアノテーションなどでInjectionしてから使用できます。
- UUID.randomUUID().toString():ユニークな値をKeyとして使用するために使用しました。UUIDについてはこちら
- new ObjectMetadata():AmazonS3で保存されるオブジェクトメタデータのことです。メタデータをカスタムするために使います。
- awsS3Client.putObject:指定したAWS S3バケットにオブジェクトをアップロードします。
- awsS3Client.setObjectAcl:AWS S3オブジェクトへのアクセスコントロールリストを指定します。
- CannedAccessControlList.PublicRead:今回はサンプルなので、誰でもHTTPでファイルを参照できるようにしました。
- CannedAccessControlListの種類や詳細についてはこちら
- awsS3Client.getResourceUrl():これで保存したリソースのURL取得が可能です。
