AWS S3 上传文件

1.引入依赖

<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.12.50</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.1000</version>
        </dependency>

 2.创建s3Client

package com.nft.util;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AwsS3Component implements InitializingBean {

    @Value("${s3.accessKey}")
    String accessKey;
    @Value("${s3.secretKey}")
    String secretKey;
    @Value("${s3.bucket.name}")
    String bucketName;

    @Value("${proxy.host}")
    String proxyHost;
    @Value("${proxy.port}")
    int proxyPort;

    public static AmazonS3 s3Client = null;


    @Override
    public void afterPropertiesSet() {
        Regions clientRegion = Regions.EU_CENTRAL_1;
        ClientConfiguration clientConfiguration = new ClientConfiguration();

        if (proxyHost != null) {
            clientConfiguration.setProxyHost(proxyHost);
            clientConfiguration.setProxyPort(proxyPort);
            clientConfiguration.setProxyUsername("");
            clientConfiguration.setProxyPassword("");
        }


        BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
        // us-west-2 is AWS Oregon
        if (proxyHost != null) {
            s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .withClientConfiguration(clientConfiguration)
                    .withPathStyleAccessEnabled(true)
                    .build();
        }else{
            s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .withPathStyleAccessEnabled(true)
                    .build();
        }
    }

}

2.调用工具进行上传

file---文件
folderName---s3系统文件名
bucketName---s3桶名称


AwsS3Component.s3Client.putObject(new PutObjectRequest(bucketName, folderName + "/" + filename, file.getInputStream(), objectMetadata)
                    .withCannedAcl(CannedAccessControlList.PublicRead));

上一篇:一次比较奇葩的 AWS 面试


下一篇:aws lambda 限额