【问题标题】:Download file from AWS S3 .NET Core 3.1 WEB APIs从 AWS S3 .NET Core 3.1 WEB API 下载文件
【发布时间】:2021-01-20 14:02:41
【问题描述】:

我正在尝试使用 AWS SDK 从 AWS S3 存储桶中获取对象。

            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;
            }

如何处理响应正文以从控制器返回文件?

控制器

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);
        }

    }

尝试了很多东西,但都没有成功

【问题讨论】:

  • 您是否看到以下内容:dotnetcurry.com/…
  • 我正在尝试处理来自 AWS 的响应正文。这是一个流
  • 您需要得到响应。您正在阅读 request.FileContent 并且想要响应内容。

标签: c# rest amazon-s3 .net-core aws-sdk-net


【解决方案1】:

需要 AWSSDK.S3 nuget 包。

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);
   }
}

文件名:- {任何目录}/{名称}.{txt | json | *}

下载文件:- {name}.{txt | json |*}

{} 用作占位符,输入您需要的文件名和扩展名。

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多