我正在从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转换为字节,我可以返回该文件。我怎么能这样做?
答案 0 :(得分:12)
以下是我为其他需要它的人找到的解决方案:
.where(m =>m.id == x.CategoryID).ToList()
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;
}
答案 1 :(得分:10)
另一种选择:
Stream rs;
using (IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client())
{
GetObjectRequest getObjectRequest = new GetObjectRequest();
getObjectRequest.BucketName = "mybucketname";
getObjectRequest.Key = "mykey";
using (var getObjectResponse = client.GetObject(getObjectRequest))
{
getObjectResponse.ResponseStream.CopyTo(rs);
}
}
答案 2 :(得分:1)
我一直努力让Alex提供的更干净的方法可以工作(不确定我缺少什么),但是我想不带Erica提供的额外ReadStream方法(尽管它可以工作)...是我的伤口:
var s3Client = new AmazonS3Client(AccessKeyId, SecretKey, Amazon.RegionEndpoint.USEast1);
using (s3Client)
{
MemoryStream ms = new MemoryStream();
GetObjectRequest getObjectRequest = new GetObjectRequest();
getObjectRequest.BucketName = BucketName;
getObjectRequest.Key = awsFileKey;
using (var getObjectResponse = s3Client.GetObject(getObjectRequest))
{
getObjectResponse.ResponseStream.CopyTo(ms);
}
var download = new FileContentResult(ms.ToArray(), "image/png"); //"application/pdf"
download.FileDownloadName = ToFilePath;
return download;
}
答案 3 :(得分:0)
Stream
现在具有异步方法。在C#8中,您可以执行以下操作:
public async Task<byte[]> GetAttachmentAsync(string objectPointer)
{
var objReq = new GetObjectRequest
{
BucketName = "bucket-name",
Key = objectPointer, // the file name
};
using var objResp = await _s3Client.GetObjectAsync(objReq);
using var ms = new MemoryStream();
await objResp.ResponseStream.CopyToAsync(ms, _ct); // _ct is a CancellationToken
return ms.ToArray();
}
这不会在发生IO时阻塞任何线程。