Java 如何通过 SDK 设置 S3 对象的内容类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23467044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:13:13  来源:igfitidea点击:

How to set the content type of an S3 object via the SDK?

javaamazon-web-servicesamazon-s3

提问by Click Upvote

I'm trying to use AWS Api to set the content type of multiple objects and to add a 'content-encoding: gzip' header to them. Here's my code for doing that:

我正在尝试使用 AWS Api 设置多个对象的内容类型并向它们添加“内容编码:gzip”标头。这是我这样做的代码:

for (S3ObjectSummary summary : objs.getObjectSummaries() )
   {
       String key = summary.getKey();
       if (! key.endsWith(".gz"))
           continue;

       ObjectMetadata metadata = new ObjectMetadata();
       metadata.addUserMetadata("Content-Encoding", "gzip");
       metadata.addUserMetadata("Content-Type", "application/x-gzip");
       final CopyObjectRequest request = new CopyObjectRequest(bucket, key, bucket, key)
               .withSourceBucketName( bucket )
               .withSourceKey(key)
               .withNewObjectMetadata(metadata);

       s3.copyObject(request);
   }

When I run this however, the following is the result:

但是,当我运行它时,结果如下:

screenshot

截屏

As you can see, the prefix x-amz-metawas added to my custom headers, and they were lower cased. And the content-typeheader was ignored, instead it put www/form-encodedas the header.

如您所见,前缀x-amz-meta已添加到我的自定义标题中,并且它们是小写的。并且content-type标题被忽略,而是www/form-encoded作为标题放置。

What can I do it to cause it to accept my header values?

我该怎么做才能让它接受我的标头值?

采纳答案by Click Upvote

Found the problem. ObjectMetadatarequires the content-type / encoding to be set explicitly rather than via addUserMetadata(). Changing the following:

发现问题了。ObjectMetadata需要显式设置内容类型/编码,而不是通过addUserMetadata()。更改以下内容:

   metadata.addUserMetadata("Content-Encoding", "gzip");
   metadata.addUserMetadata("Content-Type", "application/x-gzip");

to:

到:

       metadata.setContentEncoding("gzip");
       metadata.setContentType("application/x-gzip");

fixed this.

修复了这个。