<brad-oyler/>

02
March

Uploading an image with AWS SDK for .Net (C#)

I recently started using cloud-based hosting (AppHarbor.com) for my latest project (Mealtik.com) and I needed a remote storage solution for the images that would be uploaded by users. I was already familiar with Amazon’s Simple Storage service (AWS S3), but never actually built a .Net app that used this API for uploading images to S3.

So…here are the steps to simply get an image published\uploaded to S3.

1. First go get an account with AWS at http://aws.amazon.com/ and then go get your accessKey and SecretKey from your account.

2. Download the AWS SDK for .Net here: http://aws.amazon.com/sdkfornet/ and include the assembly AWSSDK.dll in your project.

3. Here’s the markup:
     <input type=”file” id=”fileUpload” name=”fileUpload” size=”23” />

4. Here’s the 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))
{
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName("mealtik")
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey("meals/test.jpg").InputStream = file.InputStream;
S3Response response = client.PutObject(request);
}
}



A few things to point out:
  1. I’m uploading my image (“test.jpg”) to folder (“meals”) which is in a bucket called “mealtik”.
  2. I’m setting the image permissions to “public read”.
  3. I’m using MVC, but the code should work for webforms as well.

As you can see, it’s pretty simple to do, but for some reason I couldn’t find an example of this anywhere on the interwebs. Hope this helps!

  1. bradoyler posted this