Click here to Skip to main content
15,440,014 members
Articles / Cloud
Technical Blog
Posted 8 Feb 2015

Tagged as

Stats

21.4K views
9 bookmarked

Store Files in Amazon S3 using AWS SDK in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
8 Feb 2015CPOL1 min read
Store files in Amazon S3 using AWS SDK in ASP.NET MVC

In this article, we will learn how to store files in Amazon S3 using AWS SDK in ASP.NET MVC.

Check here how to Upload Base64 data to S3 using AWS SDK in ASP.NET MVC.

What is Amazon S3

Amazon S3 (Simple Storage Service) is an online file storage web service offered by Amazon Web Services. The S3 allows uploading, storage and downloading of practically any file or object up to five gigabytes (5 GB) in size. To use Amazon S3, we must create a bucket to the store data. Each Buckets have the configuration properties like to make the objects accesses public or private.

Step 1: Install Amazon AWS SDK

To install AWS SDK for .NET, run the following command in the Package Manager Console.

Install-Package AWSSDK

Step 2: Get your Access Key ID and Secret Access Key

To use AWS SDK, first you need to get your Access Key ID and Secret Access Key. You can create using the IAM console https://console.aws.amazon.com/iam/home?#home to know more about how create your access keys. Please check the following documentation at Amazon:

Step 3: Create Bucket

Here, we can create the bucket using AWS Console.

S3 Management Console

S3 Management Console

Once the bucket is created save the bucket name in the web.config file. 
Also save your AWSAccessKey and AWSSecretKey in the web.config file.

Step 4: Using AWS SDK.Net

Upload a file using form post use the following code:

A bucket can have multiple keys. A Key can store multiple objects. In simple words, Key is folder name. Here, we are using the Key name as UPLOADS.

C#
using System;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;

namespace AmazonAWS.Controllers
{
    public class S3Controller : Controller
    {
        private static readonly string _awsAccessKey = 
        	ConfigurationManager.AppSettings["AWSAccessKey"];

        private static readonly string _awsSecretKey = 
        	ConfigurationManager.AppSettings["AWSSecretKey"];

        private static readonly string _bucketName = 
        	ConfigurationManager.AppSettings["Bucketname"];

        public ActionResult UploadToS3(HttpPostedFileBase file)
        {
            try
            {
                IAmazonS3 client;
                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
                {
                    var request = new PutObjectRequest()
                    {
                        BucketName = _bucketName,
                        CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
                        Key =  string.Format("UPLOADS/{0}", file.FileName),
                        InputStream = file.InputStream//SEND THE FILE STREAM
                    };

                    client.PutObject(request);
                }
            }
            catch (Exception ex)
            {
                

            }
            return View();
        }
    }
}

The post Store files in Amazon S3 using AWS SDK in ASP.NET MVC appeared first on Venkat Baggu Blog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) eBiz Solutions http://venkatbaggu.com/
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to prevent of error 'Access Denied' while uploading a file in AWS bucket? Pin
dawood abbas6-Mar-19 22:51
Memberdawood abbas6-Mar-19 22:51 
private static readonly string _awsAccessKey = "something";
        private static readonly string _awsSecretKey = "something";
        private static readonly string _bucketName = "something";


The above variables declared in the controller class globally.
and sending it to the AmazonS3Client method which is in uploading method below.

[HttpPost]
        public ContentResult UploadImgsAndInsertIncident()
        {
            try
            {
                foreach (string file in Request.Files)
                {
                    var uploadedFile = Request.Files[file];
                    if (uploadedFile != null)
                    {
                        AmazonS3Config S3Config = new AmazonS3Config
                        {
                            //its default region set by amazon
                            SignatureVersion = "4",
                            RegionEndpoint = RegionEndpoint.USEast1,
                            SignatureMethod = SigningAlgorithm.HmacSHA256
                        };

                        AmazonS3Client client;
                        using (client = new Amazon.S3.AmazonS3Client(_awsAccessKey, _awsSecretKey, S3Config))
                        {

                            var request = new PutObjectRequest()
                            {
                                BucketName = _bucketName,
                                CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
                                Key = string.Format("UPLOADS/{0}", uploadedFile.FileName),
                                InputStream = uploadedFile.InputStream//SEND THE FILE STREAM
                            };

                            var response = client.PutObject(request);
                            if (Convert.ToString(response.HttpStatusCode) == "OK")
                            {
                                //do what you want..
                            }
                        }
                    }
                }

            }

            catch (Exception)
            {

            }
            return Content("Sucess");
        }


at this line
var response = client.PutObject(request);
getting an exception i.e, 'Access Denied'.

so what could be the issue and what I am missing?

this is applied same as Codeproject tutorial i.e below link.

upload files to amazon s3 using asp.net mvc | Learn Share Corner[^]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.