开发者

How to set Http Header for Amazon S3 programmatically?

开发者 https://www.devze.com 2023-02-21 15:56 出处:网络
I want to set expiration date header for files which are stored in S3 by my asp.net web application. first case - during PutObject

I want to set expiration date header for files which are stored in S3 by my asp.net web application.

  • first case - during PutObject requests
  • second case - update of expiration date once a m开发者_运维技巧onth to update expiration dates.


As you are using Asp.net, I assume you are using the AWS .NET SDK.

To add the Expires(or any other http header) when uploading the object, add it as part of the PutObject request.

var client = new Amazon.S3.AmazonS3Client(AWS_Key, AWS_SecretKey);

var req = new Amazon.S3.Model.PutObjectRequest()
                 .WithFilePath(@"C:\myfile.txt")
                 .WithKey("myfile.txt")
                 .WithBucketName("mybucket");

req.AddHeader("expires", "Thu, 01 Dec 1994 16:00:00 GMT");

client.PutObject(req);

To change the header on an existing object, you need to copy the object to itself.

var req = new Amazon.S3.Model.CopyObjectRequest()
                 .WithDirective(Amazon.S3.Model.S3MetadataDirective.REPLACE)
                 .WithSourceBucket("mybucket")
                 .WithSourceKey("myfile.txt")
                 .WithDestinationBucket("mybucket")
                 .WithDestinationKey("myfile.txt");

req.AddHeader("expires", "Thu, 01 Dec 1994 16:00:00 GMT");

client.CopyObject(req);

Note: .WithDirective(Amazon.S3.Model.S3MetadataDirective.REPLACE) must be set in order to specify new headers. Otherwise the existing headers are just copied over.

More more info see the .NET SDK docs.


If you are using the AWS SDK 2.X then the "AddHeader" method is no longer available. To add a header you just modify the header collection directly.

req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";

Here is the modified example Geoff used above:

var client = new Amazon.S3.AmazonS3Client(AWS_Key, AWS_SecretKey);

var req = PutObjectRequest req= new PutObjectRequest()
{
    BucketName = "mybucket",
    Key = "myfile.txt",
    FilePath = @"C:\myfile.txt"
};

req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";

client.PutObject(req);

To change the header it's the same way:

var req = new Amazon.S3.Model.CopyObjectRequest()
{
    MetadataDirective = S3MetadataDirective.REPLACE,
    SourceBucket = "mybucket",
    SourceKey = "myfile.txt",
    DestinationBucket = "mybucket",
    DestinationKey = "myfile.txt"
};

req.Headers["expires"] = "Thu, 01 Dec 1994 16:00:00 GMT";

client.CopyObject(req);


For AWSSDK.S3 V3.* its works like this:

request.Headers.Expires = DateTime.Now.AddMinutes(2);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号