步骤一:添加依赖
首先,在Spring Boot项目中添加AWS S3相关的依赖。如果你使用Maven,可以在pom.xml
中添加以下依赖:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.17.27</version> <!-- 请根据需要选择最新版本 -->
</dependency>
步骤二:配置AWS凭证和Bucket信息
在application.properties
中配置AWS凭证和S3 Bucket的信息。
aws.s3.bucketName=your-bucket-name
aws.region=your-region
步骤三:创建S3服务类
创建一个服务类来封装与S3的交互逻辑,包括上传、下载、删除和修改文件的方法。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
@Service
public class S3Service {
private final S3Client s3Client;
private final String bucketName;
public S3Service(@Value("${aws.s3.bucketName}") String bucketName,
@Value("${aws.region}") String region) {
this.s3Client = S3Client.builder()
.region(Region.of(region))
.credentialsProvider(DefaultCredentialsProvider.create())
.build();
this.bucketName = bucketName;
}
// 上传文件到S3
public void uploadFile(String keyName, File file) {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
s3Client.putObject(request, RequestBody.fromFile(file));
}
// 从S3下载文件
public File downloadFile(String keyName) throws IOException {
GetObjectRequest request = GetObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
File tempFile = File.createTempFile("s3file-", ".tmp");
try (FileOutputStream fos = new FileOutputStream(tempFile);
ResponseInputStream<GetObjectResponse> s3Object = s3Client.getObject(request)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s3Object.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
return tempFile;
}
// 从S3中删除文件
public void deleteFile(String keyName) {
DeleteObjectRequest request = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();
s3Client.deleteObject(request);
}
// 修改S3中的文件(简单地重新上传覆盖)
public void updateFile(String keyName, File newFile) {
uploadFile(keyName, newFile);
}
// 从S3中读取文件的内容
public String readFileContent(String keyName) throws IOException {
File file = downloadFile(keyName);
return new String(Files.readAllBytes(file.toPath()));
}
}
步骤四:创建控制器类
创建一个控制器类,用于处理与S3交互的HTTP请求,如文件上传、下载、删除和更新。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@RestController
@RequestMapping("/api/s3")
public class S3Controller {
private final S3Service s3Service;
@Autowired
public S3Controller(S3Service s3Service) {
this.s3Service = s3Service;
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
try (FileOutputStream fos = new FileOutputStream(convFile)) {
fos.write(file.getBytes());
}
s3Service.uploadFile(file.getOriginalFilename(), convFile);
return "File uploaded successfully: " + file.getOriginalFilename();
}
@GetMapping("/download/{fileName}")
public String downloadFile(@PathVariable String fileName) throws IOException {
File file = s3Service.downloadFile(fileName);
return "File downloaded successfully: " + file.getAbsolutePath();
}
@DeleteMapping("/delete/{fileName}")
public String deleteFile(@PathVariable String fileName) {
s3Service.deleteFile(fileName);
return "File deleted successfully: " + fileName;
}
@PutMapping("/update")
public String updateFile(@RequestParam("file") MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
try (FileOutputStream fos = new FileOutputStream(convFile)) {
fos.write(file.getBytes());
}
s3Service.updateFile(file.getOriginalFilename(), convFile);
return "File updated successfully: " + file.getOriginalFilename();
}
@GetMapping("/read/{fileName}")
public String readFileContent(@PathVariable String fileName) throws IOException {
return s3Service.readFileContent(fileName);
}
}
步骤五:启动Spring Boot应用程序
确保所有配置和代码都正确之后,你可以启动Spring Boot应用程序。你可以使用以下命令来启动应用程序:
mvn spring-boot:run
示例操作
-
上传文件:
通过POST请求上传文件,示例如下:curl -X POST -F "file=@/path/to/your/file.txt" http://localhost:8080/api/s3/upload
-
下载文件:
通过GET请求下载文件,示例如下:curl -X GET http://localhost:8080/api/s3/download/file.txt
-
删除文件:
通过DELETE请求删除文件,示例如下:curl -X DELETE http://localhost:8080/api/s3/delete/file.txt
-
更新文件:
通过PUT请求更新文件,示例如下:curl -X PUT -F "file=@/path/to/your/file.txt" http://localhost:8080/api/s3/update
-
读取文件内容:
通过GET请求读取文件内容,示例如下:curl -X GET http://localhost:8080/api/s3/read/file.txt