How To Upload A File To Amazon S3 Using AWS SDK In MVC

AWSSDK

The AWS SDK for .NET enables .NET developers to easily work with Amazon Web Services and build scalable solutions with Amazon S3, Amazon DynamoDB, Amazon Glacier, and more.

AWS S3/S3 Bucket

Amazon's simple storage service (Amazon S3) is used as storage for the internet. It has a simple web services interface that helps developers to store and retrieve data from anywhere around the globe. It is a highly scalable, fast, inexpensive storage, reliable, and highly trusted database.

To upload data like video, documents, images, etc., we first have to create a bucket in any of the AWS regions (us-east-2, us-west-1, eu-central-1, etc.). Every object stored in Amazon S3 resides in a bucket. We can group different objects using buckets the same way as we use the directory for grouping files.

Getting Started

  • Start Visual Studio 2019
  • Create a new Project
    Get started

Search MVC in the search bar and click on ASP.NET Web Application.

MVC

Give the project name and location to save and the solution name and framework and click next.

Configure your new project

Select the MVC application from the templates and click Create.

Create a new ASP DOT NET web application

Once the project is created, right-click on Solution Explorer and click on Manage Nuget Packages search the package AWSSDK.S3, and install it.

Manage Nuget package

Search for AWSSDK.S3 in the Browse tab.

Browser

Select the version and click Install.

Version

Wait until the installation is done.

Wait unit installation

View

@{
    ViewBag.Title = "Upload a file to S3 Bucket";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to browse image and upload to S3 bucket.</p>
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}

Web.Config

<add key="AWSProfileName" value="any name for your profile"/>
<add key="AWSAccessKey" value="Key name"/>
<add key="AWSSecretKey" value="Secret key name"/>
<add key="BucketName" value="Bucket name"/>

Controller code

using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace UploadFileToS3Bucket_UsingAWSSDK.Controllers
{
    public class HomeController : Controller
    {
        private const string keyName = "updatedtestfile.txt";
        private const string filePath = null;
        // Specify your bucket region (an example region is shown).
        private static readonly string bucketName = ConfigurationManager.AppSettings["BucketName"];
        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
        private static readonly string accesskey = ConfigurationManager.AppSettings["AWSAccessKey"];
        private static readonly string secretkey = ConfigurationManager.AppSettings["AWSSecretKey"];
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
            var fileTransferUtility = new TransferUtility(s3Client);
            try
            {
                if (file.ContentLength > 0)
                {                   
                    var filePath = Path.Combine(Server.MapPath("~/Files"), Path.GetFileName(file.FileName));                                       
                    var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        FilePath = filePath,
                        StorageClass = S3StorageClass.StandardInfrequentAccess,
                        PartSize = 6291456, // 6 MB.
                        Key = keyName,
                        CannedACL = S3CannedACL.PublicRead
                    };
                    fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                    fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                    fileTransferUtility.Upload(fileTransferUtilityRequest);
                    fileTransferUtility.Dispose();
                }
                ViewBag.Message = "File Uploaded Successfully!!";
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    ViewBag.Message = "Check the provided AWS Credentials.";
                }
                else
                {
                    ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
                }
            }
            return RedirectToAction("S3Sample");
        }
    }
}

Run the application

Upload a file to s3 bucket

Browse the file from the system and hit the Upload button.

Upload

Log in to AWS go to S3 and check if the file has been uploaded or not.

Conclusion

In this article, we have learned how to upload a file to an S3 bucket using ASWSDK in MVC.


Similar Articles