问题描述
我正在尝试使用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 |*}
{} 用作占位符,输入您所需的文件名和扩展名。