ASP.NET MVC - Uploading an image to Amazon S3
Asked Answered
S

4

11

I have my image from Request.Files[0]. Now, how do I upload this image to S3? I see that in the AWS .NET API you have to specify ContentBody when putting an object which is a string. How would I get the content body of my file?

Solidary answered 23/9, 2010 at 18:55 Comment(0)
S
17
var file = Request.Files[0];
PutObjectRequest request = new PutObjectRequest();
request.BucketName = "mybucket"
request.ContentType = contentType;
request.Key = key;
request.InputStream = file.InputStream;
s3Client.PutObject(request);
Solidary answered 23/9, 2010 at 19:52 Comment(0)
P
11

Slightly more detail with how to use folders and to grant all users read-only access. Html:

C#

HttpPostedFileBase file = Request.Files[0];
   if (file.ContentLength > 0) // accept the file
        {
            string accessKey = "XXXXXXXXXXX";
            string secretKey = "122334XXXXXXXXXX";
            AmazonS3 client;
            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
            {
                MemoryStream ms = new MemoryStream();
                PutObjectRequest request = new PutObjectRequest();
      request.WithBucketName("mybucket")
     .WithCannedACL(S3CannedACL.PublicRead)
     .WithKey("testfolder/test.jpg").InputStream = file.InputStream;
       S3Response response = client.PutObject(request);
            }

More detail is available here: http://bradoyler.com/post/3614362044/uploading-an-image-with-aws-sdk-for-net-c

Paget answered 7/3, 2011 at 21:57 Comment(1)
Blog post is dead link.Akan
H
1

Most likely this is a Base64-encoded string, but you should check the S3 documentation to be sure. If it is, you should use Convert.ToBase64String() and pass it the byte array.

Here's some sample code you can try. I haven't tested it, but it should help you get the right idea:

if (Request.Files.Count >= 1) {
    var file = Request.Files[0];
    var fileContents = new byte[file.ContentLength];
    file.InputStream.Read(fileContents, 0, file.ContentLength);
    var fileBase64String = Convert.ToBase64String(fileContents);

    // now you can send fileBase64String to the S3 uploader
}
Heber answered 23/9, 2010 at 19:1 Comment(1)
That didn't work, but what did work was using file.InputStream as the InputStream property of a PutObjectRequest object. Thanks for your help!Solidary
Y
0
                PurObjectRequest request = new PutObjectRequest()
                {
                    BucketName = _bucketName,
                    CannedACL = S3CannedACL.PublicRead,
                    Key =  string.Format("folderyouwanttoplacethefile/{0}", file.FileName),
                    InputStream = file.InputStream
                };

                YourS3client.PutObject(request);
Yungyunick answered 3/10, 2016 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.