从AWS S3 .NET Core 3.1 WEB API下载文件

问题描述

我正在尝试使用AWS开发工具包从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);
        }

    }

尝试了很多事情但没有成功

解决方法

需要 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 |*}

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...