Skip to content

Instantly share code, notes, and snippets.

@TaylorAckley
Created June 16, 2017 16:36
Show Gist options
  • Save TaylorAckley/c1485ba583d2834d093134c808d5982d to your computer and use it in GitHub Desktop.
Save TaylorAckley/c1485ba583d2834d093134c808d5982d to your computer and use it in GitHub Desktop.
AWS Upload Example with Stream
[HttpPost, Route("api/aws/upload")]
public async Task<IHttpActionResult> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
Stream stream = new MemoryStream(buffer);
AwsStore store = new AwsStore();
store.UploadTest(stream, filename);
}
return Ok();
}
public class AwsStore
{
static IAmazonS3 client;
public void UploadTest(Stream buffer, string key)
{
client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
string Bucket = "lazy-s3";
string Key = key;
Stream File = buffer;
string ContentType = "text/plain";
try
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = Bucket,
Key = Key,
ContentType = ContentType,
InputStream = File
};
PutObjectResponse response = client.PutObject(request);
//return response;
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Check the provided AWS Credentials.");
Console.WriteLine(
"For service sign up go to http://aws.amazon.com/s3");
}
else
{
Console.WriteLine(
"Error occurred. Message:'{0}' when writing an object"
, amazonS3Exception.Message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment