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

22 Jan

In this post we will learn, how to save or upload Base64 data to S3 using AWS SDK in ASP.NET MVC. You can check the previous post here how to Store files in Amazon S3 using AWS SDK in ASP.NET MVC http://venkatbaggu.com/store-files-in-amazon-s3-using-aws-sdk-asp-net-mvc/

Implementation

First you need to convert the Base64 string to Byte Array and then we convert that in to Stream object and send that request to S3.

Use the following snippet of code to save Base64 or Byte Array data S3.

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(string base64String)
{
    try
    {
        IAmazonS3 client;
        byte[] bytes = Convert.FromBase64String(base64String);

        using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
        {
            var request = new PutObjectRequest
            {
                BucketName = _bucketName,
                CannedACL = S3CannedACL.PublicRead,
                Key = string.Format("UPLOADS/{0}", file.FileName)
            };
            using (var ms = new MemoryStream(bytes))
            {
                request.InputStream = ms;
                client.PutObject(request);
            }
        }
    }
    catch (Exception ex)
    {
        

    }
    return View();
}

One thought on “Upload Base64 data to S3 using AWS SDK in ASP.NET MVC

Leave a Reply

Your email address will not be published. Required fields are marked *