How To Uploading Get and Delete a File To AWS S3 Using ASP.NET MVC Core?

How To Uploading Get and Delete a File To AWS S3 Using ASP.NET MVC Core?

Add namespace

 

 We need to install the following NuGet packages:
1. AWSSDK.Extensions.NETCore.Setup
2. AWSSDK.S3

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Amazon;
using Amazon.S3;
//using Amazon.S3.IO;
using System.IO;
using Amazon.S3.Transfer;

namespace usingcsharp.helper
{
    public static class AWSS3
    {
        static string AWSAccessKey = "*******"; //AWS Access Key
        static string AWSSecretKey = "****";  //AWS Secret Key
        static string BucketName = "BucketName "; //Bucket Name
        static IAmazonS3 client = new AmazonS3Client(AWSAccessKey, AWSSecretKey, RegionEndpoint.APSoutheast1);
        
        //List Objects From Bucket Folder
        public static void GetObjFromAwsS3(string id)
        {
            string path = "" + id+ "\\";

            //S3DirectoryInfo di = new S3DirectoryInfo(client, BucketName, path);
            //IS3FileSystemInfo[] files = di.GetFileSystemInfos();
            //foreach (S3FileInfo file in files)
            //{
            //    Console.WriteLine("{file.Name}");
            //}
        }

        public static void Get_single_ObjFromAwsS3(string id, string filename)
        {
            string path = "" + id+ "\\";

            //S3DirectoryInfo di = new S3DirectoryInfo(client, BucketName, path);
            //IS3FileSystemInfo[] files = di.GetFileSystemInfos();
            //foreach (S3FileInfo file in files)
            //{
            //    Console.WriteLine("{file.Name}");
            //}
        }
        public static bool Checkif_single_ObjFromAwsS3(string id, string filename)
        {
            string path = "" + id+ "\\";
            bool exists_or_Not = false;
            //S3DirectoryInfo di = new S3DirectoryInfo(client, BucketName, path);
            //IS3FileSystemInfo[] files = di.GetFileSystemInfos();
            //foreach (S3FileInfo file in files)
            //{
            //    if (filename == file.Name)
            //    {
            //        exists_or_Not = true;
            //    }
            //}
            return exists_or_Not;
        }

        public static bool DeleteObjFromAwsS3(string id, string filename)
        {
            string path = "" + id+ "\\" + filename + "";
            bool delete_file = false;
            //// delete test.txt file    
            //S3FileInfo s3File = new S3FileInfo(client, BucketName, path);
            //if (s3File.Exists)
            //{
            //    s3File.Delete();
            //    delete_file = true;
            //}
            return delete_file;
        }

        public static void DeleteFolderFromAwsS3(string id)
        {
            // delete sub-folder    
            // string folderPath = @"high-level-folder\sub-folder\";
            string path = "" + id+ "\\";
            //S3DirectoryInfo directory = new S3DirectoryInfo(client, BucketName, path);
            //if (directory.Exists)
            //{
            //    directory.Delete(true);
            //}
        }

        public static void CreateFolderinBucketAwsS3(string foldername)
        {
            string path = "" + foldername + "";

            //S3DirectoryInfo di = new S3DirectoryInfo(client, BucketName, path);
            //if (!di.Exists)
            //{
            //    di.Create();
            //    //di.CreateSubdirectory(foldername);
            //}
        }
        public static bool sendMyFileToS3(System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
        {

            var amazonS3Config = new AmazonS3Config();
            amazonS3Config.SignatureVersion = "v4";
            amazonS3Config.SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256;// SigningAlgorithm.HmacSHA1;
            amazonS3Config.RegionEndpoint = RegionEndpoint.GetBySystemName("ap-southeast-1");


            //IAmazonS3 client = new AmazonS3Client(amazonS3Config.RegionEndpoint);
            TransferUtility utility = new TransferUtility(client);
            TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();

            if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
            {
                request.BucketName = bucketName; //no subdirectory just bucket name  
            }
            else
            {   // subdirectory and bucket name  
                request.BucketName = bucketName + @"/" + subDirectoryInBucket;
            }
            request.Key = fileNameInS3; //file name up in S3  
            request.InputStream = localFilePath;
            utility.Upload(request); //commensing the transfer  

            return true; //indicate that the file was sent  
        }
        public static bool UploadObjinBucketAwsS3(Stream file, Int32 id, string name)
        {
            string s3DirectoryName = Convert.ToString(id);
            string s3FileName = @name;
            bool a;
            // AmazonUploader myUploader = new AmazonUploader();
            a = sendMyFileToS3(file, BucketName, s3DirectoryName, s3FileName);
            return a;
        }
        public static string AWSGetImageUrl(string id, string path)
        {
            string returnUrl = "https://s3-ap-southeast-1.amazonaws.com/bucketname/" + id+ "/" + path;
            return returnUrl;
        }
    }
}

 

Other Method

 

using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace usingcsharp.Helper
{
    public class AWSS3Service
    {
        private static String accessKey = "YOUR_ACCESS_KEY_ID";
        private static String accessSecret = "YOUR_SECRET_ACCESS_KEY";
        private static String bucket = "YOUR_S3_BUCKET";
       
        static IAmazonS3 client = new AmazonS3Client(accessKey, accessSecret, RegionEndpoint.APSoutheast1);
        
       
        public static async Task<bool> UploadObjectAsync1(System.IO.Stream file, string userid, string ImageName)
        {
            bool Success = false;
            // connecting to the client
            var client = new AmazonS3Client(accessKey, accessSecret, Amazon.RegionEndpoint.EUCentral1);
            try
            {
                // get the file and convert it to the byte[]
                byte[] fileBytes = new Byte[file.Length];
                //file.OpenReadStream().Read(fileBytes, 0, Int32.Parse(file.Length.ToString()));

                //// create unique file name for prevent the mess
                //string extension = Path.GetExtension(file.FileName);
                //var fileName = ImageName + extension;

                PutObjectResponse response = null;

                //using (var stream = new MemoryStream(fileBytes))
                //{
                    var request = new PutObjectRequest
                    {
                        BucketName = bucket + @"/" + userid,
                        Key = ImageName,
                        InputStream = file,
                        //ContentType = file.Read,
                        CannedACL = S3CannedACL.PublicRead
                    };

                    response = await client.PutObjectAsync(request);
                //};

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    // this model is up to you, in my case I have to use it following;
                    Success = true;
                }
                else
                {
                    // this model is up to you, in my case I have to use it following;
                    Success = false;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            return Success;
        }
        public static async Task<bool> UploadObjectAsync(IFormFile file,string userid,string ImageName)
        {
            bool Success = false;
            // connecting to the client
            //var client = new AmazonS3Client(accessKey, accessSecret, Amazon.RegionEndpoint.EUCentral1);
            try
            {
                // get the file and convert it to the byte[]
                byte[] fileBytes = new Byte[file.Length];
                file.OpenReadStream().Read(fileBytes, 0, Int32.Parse(file.Length.ToString()));

                // create unique file name for prevent the mess
                string extension = Path.GetExtension(file.FileName);
                var fileName = ImageName + extension;

                PutObjectResponse response = null;

                using (var stream = new MemoryStream(fileBytes))
                {
                    var request = new PutObjectRequest
                    {
                        BucketName = bucket+@"/"+userid,
                        Key = fileName,
                        InputStream = stream,
                        ContentType = file.ContentType,
                        CannedACL = S3CannedACL.PublicRead
                    };

                    response = await client.PutObjectAsync(request);
                };

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    // this model is up to you, in my case I have to use it following;
                    Success = true;
                }
                else
                {
                    // this model is up to you, in my case I have to use it following;
                    Success = false;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            return Success;
        }

        public static async Task<bool> RemoveObjectAsync(String fileName)
        {
            bool Success = false;
            //var client = new AmazonS3Client(accessKey, accessSecret, Amazon.RegionEndpoint.EUCentral1);

            var request = new DeleteObjectRequest
            {
                BucketName = bucket,
                Key = fileName
            };

            var response = await client.DeleteObjectAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return Success = true;
            }
            else
            {
                return Success = false;
            }
        }
    }
}

2021-10-03