简体   繁体   中英

Download file from AWS S3 .NET Core 3.1 WEB APIs

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM