In previous article, I have mentioned about file upload in asp.net core mvc (single or multiple), now in this article, I have provided step by step procedure to upload file on Amazon Web Service (AWS) S3 bucket using C# in ASP.NET Core MVC.

Step 1: Create a ASP.NET Core MVC new project in your Visual Studio 2019 or 2017, I am using 2019 version so opening it and then selecting Create new Project, select "ASP.NET Core MVC" template, then click "Next"

amazon-s3-file-upload-asp-net-core-min.png

Name your project as shown above and click Next, keep the settings as it is, we are using .NET 5.0 version as you can see in the below image

https://res.cloudinary.com/dmsxwwfb5/image/upload/v1638626990/asp-net-core-s3-file-upload-min.png

Click "Create" and let Visual Studio Generate necessary files.

Step 2: Install Amazon S3 Nuget package, since we will be uploading files on AWS S3, we will install it's SDK, which we will make things easier for us, so navigate to "Tools" -> "Nuget Package Manager" -> "Manage Nuget packages for solution" -> Select "Browse" and then search for "AWSSDK.S3", you will see the package as shown below in the image and then install on your project/solution, by clicking "Install" button

aws-s3-sdk-file-upload-nuget-package

Step 3: We need to Create bucket on Amazon S3, if you have already created bucket, you can note down it's name and region, otherwise, Open Amazon Console , Sign in and Search for "S3", open "S3" and then Select "Create" -> Enter "New Bucket" name and select "AWS region", as shown below

select-s3-bucket-region-min.png

Note: your bucket name must be unique overall

Step 4: Now, we need to get Amazon S3 Secrey key and access key, which you can create using IAM roles in Amazon Console

  • Open the IAM console at https://console.aws.amazon.com/iam/
  • On the navigation menu, choose "Users".
  • Choose your IAM user name or Create new User, Give permission to users if you are creating new User, check below images for new User
    /iam-roles-user-aws-s3-min.png
    Assign Roles, I have assigned Full S3 access role
    give-s3-permissions-min.png

  • Once, you have created new User or select User.
  • Open the Security credentials tab, and then choose Create access key.
  • To see the new access key, choose Show. Your credentials resemble the following:
    • Access key ID: AWS1234567890
    • Secret access key: wjair/K7MDaENaaaG/K7MDasdadsENG

Step 5: Now, we have access and secret key, bucket name and region, now, navigate to your HomeController.cs file and use the below code

  [HttpPost]
        public async Task<IActionResult> UploadFileToS3(IFormFile file)
        {
            // access key id and secret key id, can be generated by navigating to IAM roles in AWS and then add new user, select permissions
            //for this example, try giving S3 full permissions
            using (var client = new AmazonS3Client("yourAccesKey", "yourSecretKey", RegionEndpoint.USWest2))
            {
                using (var newMemoryStream = new MemoryStream())
                {
                    file.CopyTo(newMemoryStream);

                    var uploadRequest = new TransferUtilityUploadRequest
                    {
                        InputStream = newMemoryStream,
                        Key = file.FileName, // filename
                        BucketName = "aws-s3-qawithexperts" // bucket name of S3
                    };

                    var fileTransferUtility = new TransferUtility(client);
                    await fileTransferUtility.UploadAsync(uploadRequest);
                }
            }
            ViewBag.Success = "File Uploaded on S3";
            return View("Index");
        }

So, complete HomeController.cs code will look like below

using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

namespace AmazonS3FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UploadFileToS3(IFormFile file)
        {
            // access key id and secret key id, can be generated by navigating to IAM roles in AWS and then add new user, select permissions
            //for this example, try giving S3 full permissions
            using (var client = new AmazonS3Client("yourAccesKey", "yourSecretKey", RegionEndpoint.USWest2))
            {
                using (var newMemoryStream = new MemoryStream())
                {
                    file.CopyTo(newMemoryStream);

                    var uploadRequest = new TransferUtilityUploadRequest
                    {
                        InputStream = newMemoryStream,
                        Key = file.FileName, // filename
                        BucketName = "aws-s3-qawithexperts" // bucket name of S3
                    };

                    var fileTransferUtility = new TransferUtility(client);
                    await fileTransferUtility.UploadAsync(uploadRequest);
                }
            }
            ViewBag.Success = "File Uploaded on S3";
            return View("Index");
        }
    }
}

Step 6: Navigate to "Index.cshtml" and use the below code, which is form created to submit file to controller method "UploadFiletoS3"

@{
    ViewData["Title"] = "Home Page";
}

<form enctype="multipart/form-data" method="post" asp-controller="Home" asp-action="UploadFileToS3">
<dl>
    <dt>
        <label>Upload File to S3</label>
    </dt>
    <dd>
        <input type="file" name="file" id="file">

    </dd>
</dl>
<input class="btn" type="submit" value="Upload" />
</form>
@if(ViewBag.Success != null)
{
    <div>@ViewBag.Success</div>
}

That's it, we are done, I have provided below gif image which sample file uploading to S3 using C# code in ASP.NET Core MVC

file-upload-on-aws-s3-csharp-aspnet-core-min.gif

In the above image, you can see there is no file on S3 Bucket initially, but after selecting file on .NET Core page, it is uploaded on S3 and can be viewed in image.

You may also like to read:

Bulk Insert in ASP.NET Core MVC using Entity Framework Core

Treeview in ASP.NET Core MVC

Model Validation in ASP.NET Core MVC

Creating GridView in ASP.NET Core MVC with Paging

Form Submit in ASP.NET Core MVC

Resize image in C# (Console application example)

Encrypt and Decrypt files in C#