简体   繁体   中英

Unable to set metadata while uploading file on S3 AWS using java SDK

I'm trying to set user-defined metadata while uploading a file on S3 aws. but it's not working.. Here is a portion of my code:

      AmazonS3 s3 = new AmazonS3Client(credentials); 
      Map<String, String> metaList = new HashMap<>();
      metaList.put("x-amz-meta-example", "true"); 

      ObjectMetadata medata = new ObjectMetadata(); 
      medata.setUserMetadata(metaList); 

      String bucketName = "bucketName"; 
      String key = "objKey"; 
      File file = new File("example.txt"); 


      try{

             s3.putObject(bucketName, key, file)
             .setMetadata(medata);
             System.out.println("Successfully uplooaded...");


         }catch(Exception e){


           System.out.println(e.getMessage());
      }

In AWS console, the file is uploaded successfully. But when I check the metaData, I'm not seing the metadata that I have set.

This works with aws sdk 1.11.x

ObjectMetadata metadata = new ObjectMetadata();
metadata.setCacheControl("max-age=2592000, must-revalidate");

PutObjectResult s3putObj = s3client.putObject(new PutObjectRequest(s3bucket,
                    filePath,
                    filetoupload)
                    .withMetadata(metadata)//set metadata
                    .withCannedAcl(CannedAccessControlList.PublicRead));

In the SDK it says not to set the "x-amz-meta-BLAH"

Amazon S3 can store additional metadata on objects by internally representing it as HTTP headers prefixed with "x-amz-meta-". Use user-metadata to store arbitrary metadata alongside their data in Amazon S3. When setting user metadata, callers should not include the internal "x-amz-meta-" prefix; this library will handle that for them. Likewise, when callers retrieve custom user-metadata, they will not see the "x-amz-meta-" header prefix.

http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/ObjectMetadata.html#setUserMetadata-java.util.Map-

s3.putObject(bucketName, key, file).setMetadata(medata);

In the above method call, you are setting metadata to the result but not for the request.

This will work:

s3.putObject(bucketName, key, new FileInputStream(file),medata)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM