使用 resourceLoader 上传到 S3 - Spring 启动

Upload to S3 with resourceLoader - Spring Boot

我正在尝试在没有 AWS SDK 的情况下将文件上传到我的 s3 存储桶,仅使用 Spring 云和 resourceLoader bean。

我有这个代码:

private fun uploadS3(awsFileName: String, content: String): String {
    val writableResource = resourceLoader.getResource(awsFileName) as WritableResource
    writableResource.outputStream.use { it.write(content.toByteArray()) }
    return writableResource.url.toString()
}

我的application.yml有这样的配置:

 cloud:
  aws:
    credentials:
      accessKey: XXXXX
      secretKey: XXXXX
      instanceProfile: false
    region:
      static: us-east-1
      auto: false
  s3:
    default-bucket: XXXXXX

我的 Spring 引导版本是:

springBootVersion = '2.0.2.RELEASE'

但我得到的只是这个错误:

There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance

而且我只是不知道如何解决这个问题。请帮帮我!

您可以使用 Spring Content S3,它在幕后使用 SimpleStorageResourceLoader

将以下依赖项添加到您的 pom.xml

pom.xml

    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>content-s3-spring-boot-starter</artifactId>
        <version>0.1.0</version>
    </dependency>

添加以下创建 SimpleStorageResourceLoader bean 的配置:

    @Autowired
    private Environment env;

    public Region region() {
        return Region.getRegion(Regions.fromName(env.getProperty("AWS_REGION")));
    }

    @Bean
    public BasicAWSCredentials basicAWSCredentials() {
        return new BasicAWSCredentials(env.getProperty("AWS_ACCESS_KEY_ID"), env.getProperty("AWS_SECRET_KEY"));
    }

    @Bean
    public AmazonS3 client(AWSCredentials awsCredentials) {
        AmazonS3Client amazonS3Client = new AmazonS3Client(awsCredentials);
        amazonS3Client.setRegion(region());
        return amazonS3Client;
    }

    @Bean
    public SimpleStorageResourceLoader simpleStorageResourceLoader(AmazonS3 client) {
        return new SimpleStorageResourceLoader(client);
    }

创建 "Store":

S3Store.java

public interface S3Store extends Store<String> {
}

自动装配您需要上传资源的商店:

@Autowired
private S3Store store;

WritableResource r = (WritableResource)store.getResource(getId());
InputStream is = // your input stream
OutputStream os = r.getOutputStream();
IOUtils.copy(is, os);
is.close();
os.close();

当你的应用程序启动时,它会看到对 spring-content-s3 和你的 S3Store 接口的依赖,并为你注入一个实现,因此你不必担心自己实现它。

HTH