AWS S3(Amazon Simple Storage Service)是亚马逊提供的一种对象存储服务,旨在提供可扩展、高可用性和安全的数据存储解决方案。以下是AWS S3的一些主要特点和功能:
要获取AWS的访问密钥(Access Key)和秘密密钥(Secret Key),请按照以下步骤操作:
访问 AWS管理控制台 并使用你的AWS账户登录。
如果你还没有用户,或者想为特定的应用创建一个新用户,可以按照以下步骤创建:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:*",
"Resource": "*"
}
]
}
将获取到的“访问密钥 ID”和“秘密访问密钥”填入你的application.properties
文件中:
cloud.aws.credentials.access-key=YOUR_ACCESS_KEY
cloud.aws.credentials.secret-key=YOUR_SECRET_KEY
通过以上步骤,你就可以获取AWS的访问密钥和秘密密钥,并在Spring Boot应用中进行配置。
要在Spring Boot应用中对接AWS S3服务,实现文件的上传和查询,你可以按照以下步骤进行:
在你的pom.xml
中添加AWS SDK的依赖:
<?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">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-s3</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.300</version> <!-- 请根据需要选择合适的版本 -->
</dependency>
</dependencies>
</project>
你可以通过环境变量、系统属性或配置文件来配置AWS凭证。以下是使用application.properties
的示例:
cloud.aws.credentials.access-key=xxxx cloud.aws.credentials.secret-key=xxxx cloud.aws.region.static=xxx cloud.aws.s3.bucket=xxx proxy.host=127.0.0.1 proxy.port=1080
创建一个配置类来初始化S3客户端:
package com.et.aws.config;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetSocketAddress;
import java.net.Proxy;
@Configuration
public class S3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Value("${proxy.host:}") // 代理主机
private String proxyHost;
@Value("${proxy.port:}") // 代理端口
private int proxyPort;
@Bean
public AmazonS3 amazonS3() {
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials));
// 如果代理主机和端口不为空,则配置代理
if (!proxyHost.isEmpty() && proxyPort > 0) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
builder.withClientConfiguration(new ClientConfiguration().withProxyHost(proxyHost).withProxyPort(proxyPort));
}
return builder.build();
}
}
创建一个服务类来处理文件的上传和查询:
package com.et.aws.service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class S3Service {
@Autowired
private AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucketName;
public String uploadFile(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
amazonS3.putObject(bucketName, fileName, inputStream, null);
return fileName;
}
public List<String> listFiles() {
ObjectListing objectListing = amazonS3.listObjects(bucketName);
List<String> fileNames = new ArrayList<>();
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
fileNames.add(objectSummary.getKey());
}
return fileNames;
}
}
创建一个控制器来处理HTTP请求:
package com.et.aws.controller;
import com.et.aws.service.S3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/api/s3")
public class S3Controller {
@Autowired
private S3Service s3Service;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
String fileName = s3Service.uploadFile(file);
return ResponseEntity.ok("File uploaded: " + fileName);
} catch (IOException e) {
return ResponseEntity.status(500).body("File upload failed: " + e.getMessage());
}
}
@GetMapping("/files")
public ResponseEntity<List<String>> listFiles() {
List<String> files = s3Service.listFiles();
return ResponseEntity.ok(files);
}
}
启动你的Spring Boot应用,并使用Postman或其他工具测试文件上传和查询功能。
/api/s3/upload
,并在请求中附加文件。
/api/s3/files
,将返回存储在S3中的文件列表。
通过以上步骤,你就可以在Spring Boot应用中成功对接AWS S3服务,实现文件的上传和查询。