3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Amazon S3

Last updated at Posted at 2021-02-18

SpringBootでS3にアップロード

Clientらしきもの

UploadService.java
    private AmazonS3 getAmazons3() {
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
                .withRegion(region)
                .build();
    }

S3にアップロード

UploadService.java
public String putObject(MultipartFile file, String fileName) {
        try {
            InputStream inputStream = file.getInputStream();
            String path = 保存する名前ここでランダムの名前生成など
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(file.getContentType());
            objectMetadata.setContentLength(Integer.valueOf(inputStream.available()).longValue());
            getAmazons3().putObject(bucketName, path, inputStream, objectMetadata);

アップロードしたものを特別取得URLを生成して返してくる
アップロードされたものを限定しないと、特別scriptなどのリンクが生成されてアクセスすると実行されてしまうので要注意!

UploadService.java
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, path)
                    .withMethod(HttpMethod.GET);

            final URL fileUrl = getAmazons3().generatePresignedUrl(generatePresignedUrlRequest);
            return fileUrl.toString();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
     }
}
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?