亚马逊S3的使用

news/2025/2/22 15:56:16/

一、下载s3browser客户端

1、进入下载页面进行下载

下载亚马逊S3客户端地址

2、使用客户端进行连接公司亚马逊服务

 连接成功之后的界面如下:

可以一目了然的看到上传之后的文件和文件目录存储结构。

二、亚马逊 AmazonS3的使用

1、引入pom依赖

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

 2、application.properties添加配置

#-------------------- S3 start -------------------
# http or https
amazonaws.s3.protocol = http
# host:port       (test1.endpoint=192.168.66.224:7480)
amazonaws.s3.endpoint = 192.168.66.224:7480
# accessKey    (test1.accessKey=123456)
amazonaws.s3.accessKey = 123456
# secretKey    (test1.secretKey=123456)
amazonaws.s3.secretKey = 123456
# maxConnections   (def=50)
amazonaws.s3.maxConnections = 50
# connectionTimeout   (def=10000)
amazonaws.s3.connectionTimeout = 10000
# socketTimeout   (def=50000)
amazonaws.s3.socketTimeout = 50000
# useGzip   (def=false)
amazonaws.s3.useGzip = false
# bucketName   (def=icollect)
amazonaws.s3.bucketName = icollect
#amazonaws.s3.template.key (def=template.xlsx)
amazonaws.s3.templateKey = template
#amazonaws.s3.template.path (def=template.xlsx)
amazonaws.s3.templatePath = D://template
#-------------------- S3 end -------------------

3 、添加配置类AmazonS3Properties

import com.amazonaws.ClientConfiguration;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;/*** @author 痞子磊*/
@NoArgsConstructor
@AllArgsConstructor
@Data
@ConfigurationProperties(prefix = "amazonaws.s3")
@Configuration
public class AmazonS3Properties {//private String regionName;private String endpoint;private String accessKey;private String secretKey;private String protocol = "http";private int maxConnections = ClientConfiguration.DEFAULT_MAX_CONNECTIONS;private int connectionTimeout = ClientConfiguration.DEFAULT_CONNECTION_TIMEOUT;private int socketTimeout = ClientConfiguration.DEFAULT_SOCKET_TIMEOUT;private boolean useGzip = ClientConfiguration.DEFAULT_USE_GZIP;
}

4、添加Bean初始化AmazonS3AutoConfiguration

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author chenxiaolei*/
//加这个注解表示为配置类
@Configuration
//能够配置Properties配置类
@EnableConfigurationProperties(AmazonS3Properties.class)
//因为在aMapper1上面标识了AMapper类型的bean只能有一个实现 @ConditionalOnMissingBean(AMapper.class),所以在进行aMapper2注册时,系统会出现上面图上的异常,这是正常的。
//当我们把 @ConditionalOnMissingBean(AMapper.class) 去掉之后,你的bean可以注册多次,这时需要用的@Primary来确定你要哪个实现;一般来说,对于自定义的配置类,我们应该加上@ConditionalOnMissingBean注解,以避免多个配置同时注入的风险。
@ConditionalOnMissingBean(value = AmazonS3.class)
@ConditionalOnProperty(name = {"amazonaws.s3.endpoint", "amazonaws.s3.access-key", "amazonaws.s3.secret-key"})
public class AmazonS3AutoConfiguration {@Autowiredprivate AmazonS3Properties amazonS3Properties;@Beanpublic AmazonS3 amazonS3() {ClientConfiguration clientConfig = new ClientConfiguration();clientConfig.setProtocol("https".equalsIgnoreCase(amazonS3Properties.getProtocol()) ? Protocol.HTTPS : Protocol.HTTP);clientConfig.setMaxConnections(amazonS3Properties.getMaxConnections());clientConfig.setConnectionTimeout(amazonS3Properties.getConnectionTimeout());clientConfig.setSocketTimeout(amazonS3Properties.getSocketTimeout());clientConfig.setUseGzip(amazonS3Properties.isUseGzip());BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(amazonS3Properties.getAccessKey(), amazonS3Properties.getSecretKey());AmazonS3 amazonS3 = new AmazonS3Client(basicAWSCredentials, clientConfig);amazonS3.setEndpoint(amazonS3Properties.getEndpoint());return amazonS3;}
}

4、指定AmazonS3FactoryBean获取bean对象


import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import lombok.Data;
import org.springframework.beans.factory.FactoryBean;/*** @author chenxiaolei*/
@Data
public class AmazonS3FactoryBean implements FactoryBean<AmazonS3> {private String endpoint;private String accessKey;private String secretKey;private String protocol = "http";private int maxConnections = ClientConfiguration.DEFAULT_MAX_CONNECTIONS;private int connectionTimeout = ClientConfiguration.DEFAULT_CONNECTION_TIMEOUT;private int socketTimeout = ClientConfiguration.DEFAULT_SOCKET_TIMEOUT;private boolean useGzip = ClientConfiguration.DEFAULT_USE_GZIP;@Overridepublic AmazonS3 getObject() {ClientConfiguration clientConfig = new ClientConfiguration();clientConfig.setProtocol("https".equalsIgnoreCase(getProtocol()) ? Protocol.HTTPS : Protocol.HTTP);clientConfig.setMaxConnections(getMaxConnections());clientConfig.setConnectionTimeout(getConnectionTimeout());clientConfig.setSocketTimeout(getSocketTimeout());clientConfig.setUseGzip(isUseGzip());BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(getAccessKey(), getSecretKey());AmazonS3 amazonS3 = new AmazonS3Client(basicAWSCredentials, clientConfig);amazonS3.setEndpoint(getEndpoint());return amazonS3;}@Overridepublic Class<?> getObjectType() {return AmazonS3.class;}
}

5、controller或者service添加配置 

@Value("${amazonaws.s3.bucketName}")
private String bucketName;
@Value("${amazonaws.s3.templateKey}")
private String templateKey;
@Value("${amazonaws.s3.templatePath}")
private String templatePath;
@Autowired
private AmazonS3 s3Client;

6、编写AmazonS3Util

package com.chuangzhen.dayu.common.util;import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @Description AmazonS3存储工具类* @Author pizilei* @Date 2021/10/29 13:36**/
@Slf4j
public class AmazonS3Util {/*** 获取Bucket** @param s3Client   S3客户端* @param bucketName 桶名* @return*/public static Bucket getBucket(AmazonS3 s3Client, String bucketName) {Bucket bucket = null;List<Bucket> buckets = s3Client.listBuckets();for (Bucket b : buckets) {if (b.getName().equals(bucketName)) {bucket = b;}}return bucket;}/*** 创建Bucket** @param s3Client   S3客户端* @param bucketName 桶名* @return*/public static Bucket createBucket(AmazonS3 s3Client, String bucketName) {Bucket bucket = null;if (s3Client.doesBucketExistV2(bucketName)) {log.info("Bucket:{} already exists.", bucketName);bucket = getBucket(s3Client, bucketName);} else {try {bucket = s3Client.createBucket(bucketName);} catch (Exception e) {log.error("createBucket", e.getMessage());}}return bucket;}/*** 文件上传** @param s3Client   S3客户端* @param bucketName 桶名* @param filePath   /data* @param fileName   文件名* @throws Exception*/public static void upload(AmazonS3 s3Client, String bucketName, String filePath, String fileName) throws Exception {Bucket bucket = createBucket(s3Client, bucketName);if (bucket == null) {log.warn("存储桶{}创建失败", bucketName);return;}File file = new File(filePath);log.info("AmazonS3 file:{},key:{}", file, fileName);s3Client.putObject(bucketName, fileName, file);}/*** 上传** @param s3Client      S3客户端* @param bucketName    桶名* @param fileName      文件名* @param multipartFile MultipartFile* @return* @throws Exception*/public static PutObjectResult upload(AmazonS3 s3Client, String bucketName, String fileName, MultipartFile multipartFile) throws Exception {Bucket bucket = createBucket(s3Client, bucketName);if (bucket == null) {log.warn("存储桶{}创建失败", bucketName);return null;}ObjectMetadata metadata = new ObjectMetadata();metadata.setContentType(multipartFile.getContentType());metadata.setContentLength(multipartFile.getSize());PutObjectResult putResult = s3Client.putObject(bucketName, fileName, multipartFile.getInputStream(), metadata);log.info("【流方式】上传MultipartFile完成,md5:{},S3文件:{}", putResult.getETag(), fileName);return putResult;}/*** 文件下载** @param s3Client       S3客户端* @param bucketName     桶名* @param fileName       文件名* @param targetFilePath 目标路径 例如:"E:\\data\\血缘解析Excel模板1个上中下游_466.xlsx"*/public static void downloadFile(AmazonS3 s3Client, String bucketName, String fileName, String targetFilePath) {S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, fileName));if (object != null) {byte[] data = null;try (InputStream input = object.getObjectContent(); FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath)) {data = new byte[input.available()];int len = 0;while ((len = input.read(data)) != -1) {fileOutputStream.write(data, 0, len);}} catch (IOException e) {e.printStackTrace();}}}/*** 文件读取流** @param s3Client   S3客户端* @param bucketName 桶名* @param fileName   文件名* @return* @throws IOException*/public static InputStream readContent(AmazonS3 s3Client, String bucketName, String fileName) throws IOException {S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, fileName));return object.getObjectContent();}}


http://www.ppmy.cn/news/203482.html

相关文章

夏普GP2Y1010AU0F灰尘传感器使用

夏普GP2Y1010AU0F灰尘传感器在STM32平台上的使用 一、传感器的概述 GP2Y1010AUOF是日本夏普公司开发的一款光学灰尘浓度检测传感器。此传感器内部成对角分布的红外发光二极管和光电晶体管&#xff0c;利用光敏原理来工作。用于检测特别细微的颗粒&#xff0c;如香烟颗粒、细微灰…

Amazon S3 功能介绍

Amazon S3 功能介绍 1 存储过程 创建用于存储数据元的桶&#xff0c;可以选择数据元所驻留的地区&#xff08;目前来说&#xff0c;选择东京、新加坡会快些&#xff0c;美国本土更便宜&#xff09;&#xff0c;上传数据元到桶&#xff0c;进行持久化存储。另外&#xff0c;可以…

spark对接aws s3以及兼容s3接口的对象存储

之前写了一篇如何让spark使用阿里云oss对象存储替代本地存储或者hdfs存储jar包&#xff0c;日志等&#xff0c;文章链接&#xff1a;spark对接oss对象存储 今天写一篇比较通用的&#xff0c;即spark对接aws s3或者其他厂商兼容s3接口的对象存储。 环境 spark环境&#xff1a;…

华为现在打败爱立信了么?

华为现在打败了爱立信了么&#xff1f; 我现在一直搞不明白华为是怎么打败爱立信的。 我刚问L一下同事&#xff0c;他们说华为是做手机的&#xff0c;没有电脑。 华为哪里有笔记本&#xff0c;又骗我 华为为啥要做笔记本电脑 华为成第二了&#xff0c;如果荣耀第一的话 华…

设计模式-责任链模式

责任链模式 问题背景解决方案&#xff1a;传统方法责任链模式基本介绍UML类图 解决方案&#xff1a;责任链模式UML类图代码示例 注意事项和细节 问题背景 学校OA系统采购审批项目&#xff1a;需求时 1&#xff09;采购员采购教学器材 2&#xff09;如果金额小于等于5000&#…

javaScript蓝桥杯-----芝麻开门

目录 一、介绍二、准备三、目标四、代码五、完成 一、介绍 在阿里巴巴和四十大盗的故事中&#xff0c;阿里巴巴因为无意中知道了开门的咒语人生发生了翻天覆地的变化&#xff0c;四十大盗也因为咒语的泄露最终丧命。芝麻开门的咒语作为重要的信息推动着故事的发展。下面由你来…

【深入浅出C#】章节 1:C#入门介绍:C#开发环境的设置和配置

一、环境准备 1.1 安装和配置.NET Core 当配置C#开发环境时&#xff0c;安装.NET Core是一个重要的步骤。以下是安装.NET Core的基本过程&#xff1a; 访问官方网站&#xff1a;打开浏览器&#xff0c;访问.NET Core的官方网站&#xff1a;https://dotnet.microsoft.com/en-u…

蔚来的痛苦远未结束

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 总结 &#xff08;1&#xff09;蔚来5月份的交付数据没有计入ES6的订单情况 &#xff08;2&#xff09;蔚来现在面临的主要问题是销售成本在不断增长&#xff0c;残酷的事实是&#xff0c;蔚来资产负债表上的现金只能维持5…