gpt4 book ai didi

c# - 如何从 S3 获取 GetObjectResponse 的字节?

转载 作者:可可西里 更新时间:2023-11-01 08:16:08 25 4
gpt4 key购买 nike

我正在从 Amazon S3 检索文件。我想将文件转换为字节,以便我可以按如下方式下载它:

var download = new FileContentResult(bytes, "application/pdf");
download.FileDownloadName = filename;
return download;

我这里有文件:

var client = Amazon.AWSClientFactory.CreateAmazonS3Client(
accessKey,
secretKey,
config
);
GetObjectRequest request = new GetObjectRequest();
GetObjectResponse response = client.GetObject(request);

我知道 response.WriteResponseStreamToFile() 但我想将文件下载到常规下载文件夹。如果我将 GetObjectResponse 转换为字节,我可以返回该文件。我该怎么做?

最佳答案

这是我为任何需要它的人找到的解决方案:

GetObjectResponse response = client.GetObject(request);
using (Stream responseStream = response.ResponseStream)
{
var bytes = ReadStream(responseStream);
var download = new FileContentResult(bytes, "application/pdf");
download.FileDownloadName = filename;
return download;
}

public static byte[] ReadStream(Stream responseStream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

关于c# - 如何从 S3 获取 GetObjectResponse 的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com