Scope
We decided to move our images on our websites from local drive to Amazon S3. This includes all our product images from the e-commerce side; as well as any images or videos that are associated to the CMS side.
Setup and Installation
AWS Toolkit for Visual Studio |
- Follow the Amazon Setup Guide to install the AWS Toolkit.
- Download and install (or NuGet) AWS SDK for .Net.
- Configuring AWS Credentials
- Use the Amazon Endpoint List to configure the end point
- The Amazon SDK API documentation is pretty easy to read.
Code
Upload an object
By using the Amazon SDK, We change our file service to put files to S3 instead of saving to local folder. It divides into 2 parts. We will prepare the PutObjectRequest and call AmazonS3Client.PutObject() to upload the file.public override HttpStatusCode UploadPicture(string targetPath, string sourcePath) { // Create a PutObject request var request = new PutObjectRequest { BucketName = bucket, Key = targetPath.ToLower(), FilePath = sourcePath, CannedACL = S3CannedACL.PublicRead }; try { using (var client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast2)) { // Put object PutObjectResponse response = client.PutObject(request); return response.HttpStatusCode; } } catch (Exception ex) { // logging and exception handling.... } return HttpStatusCode.NotFound; }
S3CannedACL is a predefined Access Control List that allows access to be set on S3 objects.
Access an object
To access an object in s3 is much easier. You will just need to know the url and have the correct ACL setup.
The URL format is in a form of http://{mybucket}.s3.amazonaws.com/{mykey}
mybucket is the bucket name and mykey is the key (file path) to the object.
mybucket is the bucket name and mykey is the key (file path) to the object.