使用resourceLoader上传到S3 - Spring Boot

时间:2018-06-15 19:14:11

标签: spring spring-boot amazon-s3 spring-cloud

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

我有这段代码:

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

My Spring Boot版本是:

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

我只是不知道如何解决这个问题。拜托,帮助我!

1 个答案:

答案 0 :(得分:1)

您可以使用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);
    }

创建“商店”:

  

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