<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>2.3.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
</dependency>
cloud:
aws:
credentials:
access-key: xxxxx
secret-key:xxxxx
s3:
endpoint: http://xxxxx
下一个示例演示如何使用资源加载器加载不同的资源。
public class SimpleResourceLoadingBean {
@Autowired
private ResourceLoader resourceLoader;
public void resourceLoadingMethod() throws IOException {
Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
Resource secondResource = this.resourceLoader.getResource("s3://myBucket/rootFolder/subFile");
InputStream inputStream = resource.getInputStream();
//read file
}
}
4.上传文件
从 Spring Framework 3.1 开始,资源加载器也可以用来上传带有org.springframework.core.io.WritableResource 接口的文件,这是接口的特殊化org.springframework.core.io.ResourceLoader。客户端可以使用该WritableResource界面上传文件。下一个示例演示使用资源加载器上传资源。
public class SimpleResourceLoadingBean {
@Autowired
private ResourceLoader resourceLoader;
public void writeResource() throws IOException {
Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
WritableResource writableResource = (WritableResource) resource;
try (OutputStream outputStream = writableResource.getOutputStream()) {
outputStream.write("test".getBytes());
}
}
}
此示例显示transferManager在应用程序中使用 来从硬盘驱动器上传文件。
public class SimpleResourceUploadingBean {
@Autowired
private AmazonS3 amazonS3;
public void withTransferManager() {
TransferManager transferManager = TransferManagerBuilder.standard()
.withS3Client(this.amazonS3)
.build();
transferManager.upload("myBucket","filename",new File("someFile"));
}
}