The Simplest S3 Upload Example with .NET
Want to learn more about AWS Lambda and .NET? Check out my A Cloud Guru course on ASP.NET Web API and Lambda.
While looking up something else, I stumbled across a few blog posts about uploading files to S3 with .NET. Some of the examples used layers of abstraction, added in extra models, or felt excessively long. The basics of sending a file to S3 are very simple as you will see.
There are two approaches.
See this blog post for more information on creating an S3 bucket.
Using the S3 TransferUtility
This is simpler of the two ways.
Create a new console application and add the AWSSDK.S3
NuGet package to use the S3 client.
1using Amazon.S3;
2using Amazon.S3.Transfer;
3
4TransferUtility transferUtility = new TransferUtility(new AmazonS3Client());
5
6await transferUtility.UploadAsync("helloWorld.txt", "bucket-for-blog-posts");
That’s all there is to it.
Using the S3 Client Directly
Create a new console application and add the AWSSDK.S3
NuGet package to use the S3 client.
Here is the code for uploading a file to S3. It uses the AWS SDK for .NET, and the S3 client, and is only a few lines long.
1using Amazon.S3;
2using Amazon.S3.Model;
3
4var s3Client = new AmazonS3Client();
5
6var putObjectRequest = new PutObjectRequest
7{
8 BucketName = "bucket-for-blog-posts", // replace with your bucket name
9 Key = "someImage.jpg",
10 FilePath = "someImage.jpg",
11 ContentType = "image/jpeg" // not necessary, but helpful
12};
13
14var putObjectResponse = await s3Client.PutObjectAsync(putObjectRequest);
15
16Console.WriteLine($"Status of put request: {putObjectResponse.HttpStatusCode}");
17Console.WriteLine($"S3 URI = s3://{putObjectRequest.BucketName}/{putObjectRequest.Key}");
- Line 3 creates the S3 client
- Lines 6-12 create a request for the file I am sending to S3
- Line 10 uses a file path, a stream can also be used
- Line 14 sends the request