Skip to content

Instantly share code, notes, and snippets.

@sethwebster
Created January 30, 2012 21:53
Show Gist options
  • Save sethwebster/1707024 to your computer and use it in GitHub Desktop.
Save sethwebster/1707024 to your computer and use it in GitHub Desktop.

Revisions

  1. sethwebster created this gist Jan 30, 2012.
    90 changes: 90 additions & 0 deletions gistfile1.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,90 @@
    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;

    }
    }
    }