使用IDEA搭建SpringBoot工程 访问Amazon S3

简述

        最近遇到了个新需求,需要去访问Amazon S3(对象存储服务器),由于之前没接触过这块压根就不太明白Amazon S3是什么东西,看到别人给的文档也没写清楚,所以网上查了很多资料才理解这是个什么东西,新手小白写了个Java测试例子。

Controller

        先创建一个包Controller,然后再在包下创建一个两个Java类,S3Client用来初始化Amazon S3,S3Controller具体使用Amazon S3:

package com.example.amazons3client.Controller;


import com.amazonaws.Protocol;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class S3Client {
    private String accessKey = "dGVzdA==";
    private String secretKey = "d097342fee95950d4f3ce9d3d60c92c9";
    private String endpoint = "test.hztesthcp.sunwoda.com";

    @Bean
    public AmazonS3 amazonS3() {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);

        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName());

        ClientConfiguration config = new ClientConfiguration();
        config.setSignerOverride("S3SignerType");
        config.setProtocol(Protocol.HTTP);
        config.withUseExpectContinue(false);
        config.disableSocketProxy();

        AmazonS3 client = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(credentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .withForceGlobalBucketAccessEnabled(true)
                .build();

        return client;
    }
}
package com.example.amazons3client.Controller;


import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@ResponseBody
public class S3Controller {

    @Autowired
    private AmazonS3 amazonS3;

    @PostMapping(value = "/uploadObject")
    public String uploadObject(MultipartFile file, String bucket, String key) {
        String fileName = file.getOriginalFilename();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentLength(file.getSize());

        try {
            PutObjectRequest request = new PutObjectRequest(bucket, key, file.getInputStream(), objectMetadata)
                    .withCannedAcl(CannedAccessControlList.BucketOwnerFullControl);
            PutObjectResult result = amazonS3.putObject(request);    // 设置文件访问权限
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getLocalizedMessage());
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
            System.out.println(e.toString());
        }

        return "uploadObject OK";
    }

    @PostMapping(value = "/createFolder")
    public String createFolder(String bucket) {
        amazonS3.createBucket(bucket);
        return "createFolder OK";
    }

    @PostMapping(value = "/deleteObject")
    public String deleteObject(String bucket, String key) {
        amazonS3.deleteObject(new DeleteObjectRequest(bucket, key));
        return "deleteObject OK";
    }
}

依赖

        使用Amazon S3需要添加依赖包,在pom.xml文件里的<dependencies>XXX</dependencies>添加依赖项:

<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.490</version>
</dependency>

配置上传文件大小限制

        在application.properties里添加以下代码:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB

Postman

        使用Postman测试一下:

        创建文件夹:

        上传对象:

        删除对象:

        资源下载地址:https://download.csdn.net/download/Ilson_/13651506   

        使用IDEA搭建SpringBoot工程以及配置Maven:https://blog.csdn.net/Ilson_/article/details/110443085       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ilson_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值