当前位置: 首页 > 工具软件 > S3 Plugin > 使用案例 >

亚马逊 s3 使用

储俊英
2023-12-01

1. 设置对象共有访问权限

存储桶策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws-cn:s3:::桶名/*"
        }
    ]
}

引入开发包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>amazon_s3</groupId>
    <artifactId>amazon_s3</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>
            <version>2.0.0-preview-12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>2.0.0-preview-12</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

1. 创建s3客户端实例

application配置

spring:
  application:
    name: amazon_s3

server:
  port: 6000

amazon:
  bucketName: lzq # 桶名
  accessKey: AKIAOPWHDAGSAIAMWB65 # accessKey
  secretKey: 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 # secretKey
  region: cn-northwest-1
package com.amazon.config.amazon;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;

@Data
public class Amazon {

    @Value("${amazon.bucketName}")
    private String bucketName;
    @Value("${amazon.accessKey}")
    private String accessKey;
    @Value("${amazon.secretKey}")
    private String secretKey;
    @Value("${amazon.region}")
    private String region;
}

package com.amazon.config.amazon;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

@Configuration
@Component
public class AmazonConfiguration {

    @Bean
    public Amazon amazonModel(){
        Amazon amazon = new Amazon();
        return amazon;
    }

    @Bean
    public S3Client s3client(Amazon amazon) {
        AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(
                amazon.getAccessKey(),
                amazon.getSecretKey());
        S3Client s3Client = S3Client.builder().region(Region.of(amazon.getRegion())).credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials)).build();
        return s3Client;
    }
}

2. 上传实现

package com.amazon.service.impl;

import com.amazon.service.UploadService;
import com.amazon.config.amazon.Amazon;
import com.amazon.config.result.WebResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private S3Client s3Client;
    @Autowired
    private Amazon amazon;


    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public WebResult<String> uploadFile(MultipartFile file) {
        try {
            String loadName = file.getOriginalFilename();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dirName = format.format(new Date());
            String imgName = new Date().getTime() +  loadName;
            String filename= "/img/" + dirName + "/" + imgName;
            logger.info("---------------- START UPLOAD FILE ----------------");
            logger.info("Uploading to bucket '" + amazon.getBucketName());
            PutObjectResponse putObjectResponse = s3Client.putObject(PutObjectRequest.builder().bucket(amazon.getBucketName()).key(filename).build(), RequestBody.fromBytes(file.getBytes()));
            logger.info("===================== Upload File - Done! =====================");
            String httpUrl = "https://ydfx.s3.cn-northwest-1.amazonaws.com.cn"+filename;
            return WebResult.successReturnData(httpUrl,"上传成功");
        } catch (Exception e) {
            logger.info("Exception e:" + e.toString());
        }
        return null;
    }
}

 类似资料: