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 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 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 region (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 same way as we use the directory for grouping files.
 
Getting Started,
  • Start Visual Studio 2019
  • Create a new Project
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Search MVC in search bar and click on ASP.NET Web Application.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Give project name and location to save and solution name and framework and click next.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Select MVC application from templates and click Create.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Once project is created, right click to solution explorer and click on Manage Nuget Packages and search the package AWSSDK.S3 and install it.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Search for AWSSDK.S3 in Browse tab.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Select version and click install.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Wait until installation is done.
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
View
  1. @{  
  2.     ViewBag.Title = "Upload a file to S3 Bucket";  
  3. }  
  4. <h2>@ViewBag.Title.</h2>  
  5. <h3>@ViewBag.Message</h3>  
  6.   
  7. <p>Use this area to browse image and upload to S3 bucket.</p>  
  8. @using (Html.BeginForm("UploadFile""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  9. {  
  10.     <div>  
  11.         @Html.TextBox("file"""new { type = "file" }) <br />  
  12.         <input type="submit" value="Upload" />  
  13.         @ViewBag.Message  
  14.     </div>  
  15. }    
Web.Config
  1. <add key="AWSProfileName" value="any name for your profile"/>  
  2.     <add key="AWSAccessKey" value="Key name"/>  
  3.     <add key="AWSSecretKey" value="Secret key name"/>  
  4.     <add key="BucketName" value="Bucket name"/>  
Controller code
  1. using Amazon;  
  2. using Amazon.Runtime;  
  3. using Amazon.S3;  
  4. using Amazon.S3.Model;  
  5. using Amazon.S3.Transfer;  
  6. using System;  
  7. using System.Configuration;  
  8. using System.IO;  
  9. using System.Web;  
  10. using System.Web.Mvc;  
  11. namespace UploadFileToS3Bucket_UsingAWSSDK.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         private const string keyName = "updatedtestfile.txt";  
  16.         private const string filePath = null;  
  17.         // Specify your bucket region (an example region is shown).  
  18.         private static readonly string bucketName = ConfigurationManager.AppSettings["BucketName"];  
  19.         private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;  
  20.         private static readonly string accesskey = ConfigurationManager.AppSettings["AWSAccessKey"];  
  21.         private static readonly string secretkey = ConfigurationManager.AppSettings["AWSSecretKey"];  
  22.   
  23.         public ActionResult Index()  
  24.         {  
  25.             return View();  
  26.         }          
  27.   
  28.         [HttpGet]  
  29.         public ActionResult UploadFile()  
  30.         {  
  31.             return View();  
  32.         }  
  33.   
  34.         [HttpPost]  
  35.         public ActionResult UploadFile(HttpPostedFileBase file)  
  36.         {  
  37.             var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);  
  38.   
  39.             var fileTransferUtility = new TransferUtility(s3Client);  
  40.             try  
  41.             {  
  42.                 if (file.ContentLength > 0)  
  43.                 {                      
  44.                     var filePath = Path.Combine(Server.MapPath("~/Files"),Path.GetFileName(file.FileName));                      
  45.                     var fileTransferUtilityRequest = new TransferUtilityUploadRequest  
  46.                     {  
  47.                         BucketName = bucketName,  
  48.                         FilePath = filePath,  
  49.                         StorageClass = S3StorageClass.StandardInfrequentAccess,  
  50.                         PartSize = 6291456, // 6 MB.  
  51.                         Key = keyName,  
  52.                         CannedACL = S3CannedACL.PublicRead  
  53.                     };  
  54.                     fileTransferUtilityRequest.Metadata.Add("param1""Value1");  
  55.                     fileTransferUtilityRequest.Metadata.Add("param2""Value2");  
  56.                     fileTransferUtility.Upload(fileTransferUtilityRequest);  
  57.                     fileTransferUtility.Dispose();  
  58.                 }  
  59.                 ViewBag.Message = "File Uploaded Successfully!!";  
  60.             }  
  61.   
  62.             catch (AmazonS3Exception amazonS3Exception)  
  63.             {  
  64.                 if (amazonS3Exception.ErrorCode != null &&  
  65.                     (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")  
  66.                     ||  
  67.                     amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))  
  68.                 {  
  69.                     ViewBag.Message = "Check the provided AWS Credentials.";  
  70.                 }  
  71.                 else  
  72.                 {  
  73.                     ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;  
  74.                 }  
  75.             }  
  76.             return RedirectToAction("S3Sample");  
  77.         }   
  78.    }  
  79. }  
Run the application,
 
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Browse file from system and hit Upload button.
How To Upload A File To Amazon S3 Using AWS SDK In MVC
 
Login to AWS and go to S3 and check if file has been uploaded or not.
 

Conclusion

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


Similar Articles