java 将多个文件上载到S3存储桶并返回其URL路径和名称

xzlaal3s  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(343)

我使用下面的代码上传一个文件到S3 bucket,但是我想在响应中得到objectUrl,它包含文件的S3 URL,我该怎么做呢?

try {
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
        .withRegion(region)
        .withCredentials(new ProfileCredentialsProvider())
        .build();
    TransferManager tm = TransferManagerBuilder.standard()
        .withS3Client(s3Client)
        .build();

    // TransferManager processes all transfers asynchronously,
    // so this call returns immediately.
    Upload upload = tm.upload(mediaBucket, keyName, new File(filePath));
    System.out.println("Object upload started");

    // Optionally, wait for the upload to finish before continuing.
    upload.waitForCompletion();
    System.out.println("Object upload complete");
} catch (AmazonServiceException e) {
    e.printStackTrace();
} catch (SdkClientException e) {
    e.printStackTrace();
}
mkh04yzy

mkh04yzy1#

看起来没有办法做到这一点在一个单一的操作,你需要上传文件,然后提取网址分开。
最新的API在Upload接口中有一个waitForUploadResult()方法,该方法返回一个UploadResult对象,该对象包含getBucketName()和getKey()方法,然后可以使用这些方法通过S3Utilities类(包含getUrl()方法)获取URL。

try {
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
        .withRegion(region)
        .withCredentials(new ProfileCredentialsProvider())
        .build();
    TransferManager tm = TransferManagerBuilder.standard()
        .withS3Client(s3Client)
        .build();

    Upload upload = tm.upload(mediaBucket, keyName, new File(filePath));
    UploadResult uploadResult = upload.waitForUploadResult();
    
    URL fileUrl = s3Client
        .utilities()
        .getUrl(builder -> 
            builder
                .bucket(uploadResult.getBucketName())
                .key(uploadResult.getKey())
         );
    
    // do something with URL

} catch (AmazonServiceException e) {
    e.printStackTrace();
} catch (SdkClientException e) {
    e.printStackTrace();
}

我通过查看文档和this post获得了这些信息。

相关问题