TechieClues . TechieClues .
Updated date Aug 27, 2022
We will learn how to download the file from AWS S3 Bucket using ASP.NET Core.

In this article, we will see how to download the file from AWS S3 Bucket using ASP.NET Core. Please read the below articles before continuing to this article,

How to download the files from AWS S3 Bucket using ASP.NET Core?

Step 1: 

We have created the S3 bucket in AWS and uploaded the file as shown below,

 

Step 2: 

Create a new controller, right-click "Controller" folder -> Add -> Controller as shown below,

Enter the controller name in the below dialog and click Add.

Step 3:

Add the below code in the new controller "DownloadS3File" as shown below,

using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace AwsFileOperationsCore.Controllers
{
    [Route("api/download")]
    [ApiController]
    public class DownloadS3File : Controller
    {      
        [HttpGet]
        public async Task<IActionResult> DownloadFile(string fileName)
        {
            try
            {
                // You can generate the 'access key id' and 'secret key id, when you create the IAM user in AWS.
                // Region endpoint should be same as the bucket region
                using (var amazonS3client = new AmazonS3Client("ACCESS_KEY_ID", "SECRET_KEY_ID", RegionEndpoint.APSoutheast2))
                {
                    var transferUtility = new TransferUtility(amazonS3client);

                    var response = await transferUtility.S3Client.GetObjectAsync(new GetObjectRequest()
                    {
                        // Bucket Name
                        BucketName = "my-bucket-1425",
                        // File Name
                        Key = fileName
                    });
                    // Return File not found if the file doesn't exist
                    if (response.ResponseStream == null)
                    {
                        return NotFound();
                    }
                    return File(response.ResponseStream, response.Headers.ContentType, fileName);
                }
             
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || 
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new Exception("Please check the AWS Credentials.");
                }
                else
                {
                    throw new Exception(amazonS3Exception.Message);
                }
            }
        }
    }
}

You have to copy the Access key ID and Secret access key from the AWS console and paste it into the above place. The region endpoint should be the same as your S3 bucket region. Also, don't forget to update the bucket name.

  • GetObjectAsync is used to get the specified objects from the AWS.
  • TransferUtility provides a simple API for uploading content to or downloading content from Amazon S3. 

Step 4: 

Open Chrome browser and enter the below URL,

https://localhost:<PORT_NUMBER>/api/download?fileName=<FILE_NAME>

 

ABOUT THE AUTHOR

TechieClues .
TechieClues .
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!