Upload file to S3 with ASP.NET
#
I suppose the subject pulls no punches with what we’re going to do. We are going to have simple form with a file upload and a button. Once we hit the button, whatever file was selected is going to ride the magic internet carpet and appear in an Amazon S3 bucket.
WebForm:
1.
2.
3.
Code behind:
1.
2. protected void Button1_Click(object sender, EventArgs e)
3. {
4. string result = Program.GetServiceOutput();
5. Label1.Text = result;
6. }
7.
Class file for AWSCalls;
1.
2. using Amazon; // these are part of the AWSSDK.dll that you add to the project
3. using Amazon.S3;
4. using Amazon.S3.Model;
5. ....
6. public static void SendFileToS3(string filename, Stream ImgStream)
7. {
8. string accessKey = "Access Key here!";
9. string secretAccessKey = "Secret Key goes here!";
10. string bucketName = "Bucket Name goes Here!";
11. string keyName = filename;
12.
13. AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretAccessKey);
14. PutObjectRequest request = [new][1] PutObjectRequest();
15.
16. request.WithInputStream(ImgStream);
17.
18. request.WithBucketName(bucketName);
19. request.WithKey(keyName);
20. request.StorageClass = S3StorageClass.ReducedRedundancy; //set storage to reduced redundancy
21. client.PutObject(request);
22. }
So there you have it! We take a file, throw it into a page…. and that page does a heave-ho to Amazon S3. It also goes the extra step to set it to ReducedRedundancy to save you a pretty penny.