Download file from AWS S3 .NET Core 3.1 WEB APIs

5.2k views Asked by At

I am trying to get an object from AWS S3 bucket using AWS SDK.

            using(GetObjectResponse response = await client.GetObjectAsync(request))
            using (Stream responseStream = response.ResponseStream)
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string contentType = response.Headers["Content-Type"];
                responseBody = reader.ReadToEnd();
                AWSFile file = new AWSFile();
                file.ContentType = contentType;
                file.FileContent = responseBody
                return file;
            }

How can I process the response body to return a file from the controller?

Controller

public async Task<object> DownloadAttachment(string filename)
    {
        try
        {
            var request = await _requestService.DownloadAttachmentAsync(filename);
            return  File(request.FileContent,request.ContentType, "Vue Cheat Sheet.pdf");

        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }

    }

Tried many things but could not succeed

1

There are 1 answers

0
Aman singh Parihar On

AWSSDK.S3 nuget package is required.

public class DownloadFileController: ControllerBase
{
   IAmazonS3 S3Client {get;set;}
   string BucketName ="**your bucket name**";
   public DownloadFileController(IAmazonS3 S3Client)
   {
      this.S3Client = S3Client;
   }
  
   public async Task DownloadFileAsync(string filename,string downloadfile)
   {
       TransferUtility transferUtility = new TransferUtility(S3Client);
       await transferUtility.DownloadAsync(downloadfile,BucketName,filename);
   }
}

filename:- {any directory}/{name}.{txt | json | *}

downloadfile:- {name}.{txt | json |*}

{} are used as placeholder, put your required filename and extension.