Created
January 30, 2012 21:53
-
-
Save sethwebster/1707024 to your computer and use it in GitHub Desktop.
S3 Upload Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment