首页 > 解决方案 > 使用 S3Client 在 S3 上重命名文件名

问题描述

我尝试重命名 AWS 驱动器上的文件名。我与 AWS 的连接已配置。我准备了一段代码,它应该复制具有更改文件名的新文件,但它复制了具有未更改文件名的文件。

void updateFileName(String key, String newKey, String newName) {
    CopyObjectRequest copyReq = CopyObjectRequest.builder()
            .copySource(bucket + "/" + key)
            .destinationBucket(bucket)
            .destinationKey(newKey)
            .contentDisposition("attachment; filename=" + newName)
            .build();

    s3Client.copyObject(copyReq);
}

标签: javaamazon-web-servicesamazon-s3

解决方案


我找到了解决方案。在CopyObjectRequest我添加的生成器中.metadataDirective(MetadataDirective.REPLACE)。代码应如下所示:

void updateFileName(String key, String newKey, String newName) {
CopyObjectRequest copyReq = CopyObjectRequest.builder()
        .copySource(bucket + "/" + key)
        .destinationBucket(bucket)
        .destinationKey(newKey)
        .contentDisposition("attachment; filename=" + newName)
        .metadataDirective(MetadataDirective.REPLACE)
        .build();

s3Client.copyObject(copyReq);}

推荐阅读