Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon S3 .NET Core how to upload a file

I would like to upload a file with Amazon S3 inside a .NET Core project. Is there any reference on how to create and use an AmazonS3 client? All i can find in AmazonS3 documentation for .Net Core is this(http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html) which is not very helpfull.

like image 200
kostas Avatar asked May 09 '17 09:05

kostas


2 Answers

I did using IFormFile, like this:

(You need to install AWSSDK.S3)

public async Task UploadFileToS3(IFormFile file)
{
    using (var client = new AmazonS3Client("yourAwsAccessKeyId", "yourAwsSecretAccessKey", RegionEndpoint.USEast1))
    {
        using (var newMemoryStream = new MemoryStream())
        {
            file.CopyTo(newMemoryStream);

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = newMemoryStream,
                Key = file.FileName,
                BucketName = "yourBucketName",
                CannedACL = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);
        }
    }
}
like image 57
Tiago Ávila Avatar answered Sep 23 '22 18:09

Tiago Ávila


For simple file uploading in a .netcore project, I followed this link.

After finishing the simple file upload procedure, I followed the documentation on this and this links, which were very helpful. Following two links were also helpful for a quick start.

  1. https://github.com/awslabs/aws-sdk-net-samples/blob/master/ConsoleSamples/AmazonS3Sample/AmazonS3Sample/S3Sample.cs

  2. http://www.c-sharpcorner.com/article/fileupload-to-aws-s3-using-asp-net/

This was my final code snippets in the controller for file upload (I skipped the view part, which is elaborately explained in the link shared above).

[HttpPost("UploadFiles")]
public IActionResult UploadFiles(List<IFormFile> files)
{
     long size = files.Sum(f => f.Length);

     foreach (var formFile in files)
     {
           if (formFile.Length > 0)
           {
                var filename = ContentDispositionHeaderValue
                        .Parse(formFile.ContentDisposition)
                        .FileName
                        .TrimStart().ToString();
                filename = _hostingEnvironment.WebRootPath + $@"\uploads" + $@"\{formFile.FileName}";
                size += formFile.Length;
                using (var fs = System.IO.File.Create(filename))
                {
                     formFile.CopyTo(fs);
                     fs.Flush();
                }//these code snippets saves the uploaded files to the project directory

                 uploadToS3(filename);//this is the method to upload saved file to S3

            }
      }

      return RedirectToAction("Index", "Library");
}

This is the method to upload files to Amazon S3:

        private IHostingEnvironment _hostingEnvironment;
        private AmazonS3Client _s3Client = new AmazonS3Client(RegionEndpoint.EUWest2);
        private string _bucketName = "mis-pdf-library";//this is my Amazon Bucket name
        private static string _bucketSubdirectory = String.Empty;

        public UploadController(IHostingEnvironment environment)
        {
            _hostingEnvironment = environment;
        }


        public void uploadToS3(string filePath)
        {
            try
            {
                TransferUtility fileTransferUtility = new
                    TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.EUWest2));

                string bucketName;


                if (_bucketSubdirectory == "" || _bucketSubdirectory == null)
                {
                    bucketName = _bucketName; //no subdirectory just bucket name  
                }
                else
                {   // subdirectory and bucket name  
                    bucketName = _bucketName + @"/" + _bucketSubdirectory;
                }


                // 1. Upload a file, file name is used as the object key name.
                fileTransferUtility.Upload(filePath, bucketName);
                Console.WriteLine("Upload 1 completed");


            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine(s3Exception.Message,
                                  s3Exception.InnerException);
            }
        }

This was all for uploading files in Amazon S3 bucket. I worked on .netcore 2.0 and also, don't forget to add necessary dependencies for using Amazon API. These were:

  1. AWSSDK.Core
  2. AWSSDK.Extensions.NETCore.Setup
  3. AWSSDK.S3

Hope, this would help.

like image 41
Tasnim Fabiha Avatar answered Sep 23 '22 18:09

Tasnim Fabiha