using System; using System.Collections.Generic; using System.Linq; using System.Web; using Amazon.S3.Transfer; using System.Collections.Specialized; using System.Configuration; using Amazon.S3.Model; using System.IO; using Amazon.S3.Util; namespace LettersToPushkin.Models { public class AmazonS3ImageUploadUtility { public const int FIVE_MINUTES = 5 * 60 * 1000; TransferUtility _transferUtility; string _bucket; string _uploadFile; string _uploadDirectory; public AmazonS3ImageUploadUtility() { this.loadConfiguration(); } private void loadConfiguration() { NameValueCollection appConfig = ConfigurationManager.AppSettings; if (string.IsNullOrEmpty(appConfig["AWSAccessKey"])) { throw new ConfigurationErrorsException("The AWSAccessKey must be defined"); } if (string.IsNullOrEmpty(appConfig["AWSSecretKey"])) { throw new ConfigurationErrorsException("The AWSSecretKey must be defined"); } if (string.IsNullOrEmpty(appConfig["AWSS3Bucket"])) { throw new ConfigurationErrorsException("The AWSS3Bucket must be defined"); } if (string.IsNullOrEmpty(appConfig["AWSS3LetterFolder"])) { throw new ConfigurationErrorsException("The AWSS3LetterFolder must be defined"); } this._transferUtility = new TransferUtility(appConfig["AWSAccessKey"], appConfig["AWSSecretKey"]); // Update the Bucket to the optionally supplied Bucket from the App.config. this._bucket = appConfig["AWSS3Bucket"]; this._uploadDirectory = appConfig["AWSS3LetterFolder"]; } public Uri UploadFile(string LocalFileName) { try { // Make sure the bucket exists var putBucketRequest = new PutBucketRequest().WithBucketName(this._bucket); putBucketRequest.AddHeaders(AmazonS3Util.CreateHeaderEntry("x-amz-acl", "public-read")); this._transferUtility.S3Client.PutBucket(putBucketRequest); TransferUtilityUploadRequest request = new TransferUtilityUploadRequest() .WithBucketName(this._bucket) .WithFilePath(LocalFileName) .WithCannedACL(S3CannedACL.PublicRead) .WithTimeout(FIVE_MINUTES); this._transferUtility.Upload(request); return new Uri(string.Format("https://s3.amazonaws.com/us_ltp/{0}", Path.GetFileName(LocalFileName))); } catch (Exception e) { throw e; } finally { } return null; } } }