Skip to content

Instantly share code, notes, and snippets.

@AlexShkor
Created July 17, 2013 08:16
Show Gist options
  • Save AlexShkor/6018730 to your computer and use it in GitHub Desktop.
Save AlexShkor/6018730 to your computer and use it in GitHub Desktop.
Amazon S3 helper
public class AmazonS3Helper
{
private readonly string _amazonAccessKey;
private readonly string _amazonSecretKey;
private const string BucketName = "zertisedpm";
public AmazonS3Helper(string amazonAccessKey, string amazonSecretKey )
{
_amazonAccessKey = amazonAccessKey;
_amazonSecretKey = amazonSecretKey;
}
public string GenerateFilename(string originalFileName)
{
return ObjectId.GenerateNewId().ToString() + Path.GetExtension(originalFileName);
}
public void UploadFile(string fileName, Stream inputStream)
{
using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(_amazonAccessKey, _amazonSecretKey))
{
var request = new PutObjectRequest()
.WithBucketName(BucketName)
.WithCannedACL(S3CannedACL.Private)
.WithKey("docs/" + fileName);
request.InputStream = inputStream;
client.PutObject(request);
}
}
public byte[] DownloadFile(string fileName)
{
byte[] fileBytes;
using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(_amazonAccessKey, _amazonSecretKey))
{
var request = new GetObjectRequest()
.WithBucketName(BucketName)
.WithKey("docs/" + fileName);
using (var response = client.GetObject(request))
{
var numBytesRead = 0;
var numBytesToRead = (int)response.ContentLength;
fileBytes = new byte[numBytesToRead];
using (var stream = new MemoryStream())
{
while (numBytesToRead > 0)
{
var n = response.ResponseStream.Read(fileBytes, numBytesRead, numBytesToRead);
stream.Write(fileBytes, numBytesRead, n);
if (n == 0) break;
numBytesRead += n;
numBytesToRead -= n;
}
}
}
}
return fileBytes;
}
public void DeleteFile(string fileName)
{
using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(_amazonAccessKey, _amazonSecretKey))
{
var request = new DeleteObjectRequest()
.WithBucketName(BucketName)
.WithKey("docs/" + fileName);
client.DeleteObject(request);
}
}
public IEnumerable<T> BuildUploadFilesResponse<T>(HttpFileCollectionBase files, Func<string, string, T> itemBuilder)
{
for (int i = 0; i < files.Count; i++)
{
var file = files[i];
var filename = GenerateFilename(file.FileName);
if (file.ContentLength > 0)
{
UploadFile(filename, file.InputStream);
}
yield return itemBuilder(filename, file.FileName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment