当前位置:  开发笔记 > 编程语言 > 正文

如何从S3获取GetObjectResponse的字节?

如何解决《如何从S3获取GetObjectResponse的字节?》经验,为你挑选了2个好方法。

我正在从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转换为字节,我可以返回该文件.我怎样才能做到这一点?



1> Erica Stockw..:

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

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



2> Alex..:

另一种选择:

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

推荐阅读
N个小灰流_701
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有