Wednesday, December 23, 2020

Save a file in s3 Bucket with ASP.net Core and lambda

 First create a bucket and get the config  and for lambda please consider this post for setting otherwise your image or video  get corrupted on S3 bucket 



 "Bucket": {
    "AWSAccessKey": "",
    "AWSSecretKey": "",
    "BucketName": "BucketName",
    "FilePathImages": "MobileAPI/email_images",
    "FilePathVideo": "MobileAPI/email_videos"
  },

 In bucket I create a sub folder with MobileAPI that contains two folder email_images and email_videos because I want to save video and images in a separate folder

 

Lets jump in to the code make a new controller name what ever you want use this name as to hit this method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Amazon.S3;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace MobileAPILambda.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class send_contact_messageController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public static IWebHostEnvironment _environment;
        public send_contact_messageController(IWebHostEnvironment environment,
            IConfiguration configuration)
        {
            _environment = environment;
            _configuration = configuration;
        }
        public class FileUploadAPI
        {
            public IFormFile image { get; set; }
        }
        public class FileUploadvideoAPI
        {
            public IFormFile video { get; set; }
        }
        [HttpPost]
        public async Task<string> Post([FromForm] FileUploadvideoAPI objVideoFile, [FromForm] FileUploadAPI objFile)
        {
            string jsonString = "";
            try
            {
                        string AWS_bucketName = Convert.ToString(_configuration["Bucket:BucketName"]);
                        string AWS_accessKey = Convert.ToString(_configuration["Bucket:AWSAccessKey"]);
                        string AWS_secretKey = Convert.ToString(_configuration["Bucket:AWSSecretKey"]);
                        string FilePathImages = Convert.ToString(_configuration["Bucket:FilePathImages"]);
                        string FilePathVideo = Convert.ToString(_configuration["Bucket:FilePathVideo"]);
                        #region local save
                        /* FileStream fileStream = System.IO.File.Create(objFile.image.FileName);
                         using (FileStream fileStream1 = System.IO.File.Create(_environment.ContentRootPath + "\\Uploads\\" + objFile.image.FileName))
                         {
                             objFile.image.CopyTo(fileStream);
                             fileStream.Flush();
                         }
                         using (FileStream fileStream2 = System.IO.File.Create(_environment.ContentRootPath + "\\Uploads\\" + objVideoFile.video.FileName))
                         {
                             objVideoFile.video.CopyTo(fileStream);
                             fileStream.Flush();
                         } */
                        #endregion
                        string email_images = await UploadFileToAWSAsync(AWS_accessKey, AWS_secretKey, AWS_bucketName, FilePathImages, objFile.image);
                        string email_video = await UploadFileToAWSAsync(AWS_accessKey, AWS_secretKey, AWS_bucketName, FilePathVideo, objVideoFile.video);

// This is the return Json i want to send as response
                        Result.message = "Upload!";
                        Result.success = true;
                        var options = new JsonSerializerOptions
                        {
                            WriteIndented = true,
                        };
                        jsonString = System.Text.Json.JsonSerializer.Serialize(Result, options);
                   
                }
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
            return jsonString;
        }
        protected async Task<string> UploadFileToAWSAsync(string AWS_accessKey, string AWS_secretKey, string AWS_bucketName, string AWS_defaultFolder, IFormFile myfile)
        {
            var result = "";
            try
            {
                var s3Client = new AmazonS3Client(AWS_accessKey, AWS_secretKey, Amazon.RegionEndpoint.APNortheast2);
                var bucketName = AWS_bucketName;
                var keyName = AWS_defaultFolder;
                keyName = keyName + "/" + myfile.FileName;
                var fs = myfile.OpenReadStream();
                var request = new Amazon.S3.Model.PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    InputStream = fs,
                    ContentType = myfile.ContentType,
                    CannedACL = S3CannedACL.Private
                };
                await s3Client.PutObjectAsync(request);
                result = string.Format("https://{0}.s3.ap-northeast-2.amazonaws.com/{1}", bucketName, keyName);
            }
            catch (AmazonS3Exception exception)
            {
                result = exception.Message;
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

    }
}