从AWS S3获取对象作为流

jrn*_*jrn 9 c# amazon-s3 amazon-web-services

我试图弄清楚是否有可能返回从我的AWS S3存储桶中获取的对象的某种流(可能是内存流?)。

S3存储桶包含许多不同类型的图像,文档等。所有这些都应在我的网站上使用。但是,我不想显示我的AWS S3存储桶的路径。
这就是为什么我试图创建一个流并动态显示图像和可下载文档的原因,而不是完整路径。这有意义吗?:-)

我正在使用C#/。NET AWS开发工具包。

期待听到任何指向的想法和指示!

public FileStream GetFile(string keyName)
{
    using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast2))
    {
        GetObjectRequest request = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = keyName
        };

        using (GetObjectResponse response = client.GetObject(request))
        using (Stream responseStream = response.ResponseStream)
        using (StreamReader reader = new StreamReader(responseStream))
        {
            // The following outputs the content of my text file:
            Console.WriteLine(reader.ReadToEnd());
            // Do some magic to return content as a stream
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

moo*_*isy 18

在.NET 4中,您可以使用Stream.CopyTo将ResponseStream的内容(即Amazon.Runtime.Internal.Util.MD5Stream)复制到MemoryStream中。

GetObjectResponse response = await client.GetObjectAsync(bucketName, keyName);
MemoryStream memoryStream = new MemoryStream();

using (Stream responseStream = response.ResponseStream)
{
    responseStream.CopyTo(memoryStream);
}

return memoryStream;
Run Code Online (Sandbox Code Playgroud)

除了使用正在创建的请求client.GetObjectAsync(bucketName, keyName)进行调用以外GetObject,哪里是替代方法。

  • 您可能需要对其进行编辑以显示“ ResponseStream”的“ Dispose”。AWS文档指示“为了使用此流而不会泄漏...请在using块内包装对流的访问”。 (6认同)

Opt*_*ion 6

更便宜的方法是使用 S3 中对象的预签名 URL。这样您就可以将过期的 URL 返回到您的资源,并且不需要进行任何流复制。所需内存非常低,因此您可以使用非常小且便宜的虚拟机。

这种方法只适用于少数资源和少数客户。随着更多请求,您可能会达到 AWS API 限制。

using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast2))
{
    var request = new GetPreSignedUrlRequest()
    {
        BucketName = bucketName,
        Key = keyName,
        Expires = DateTime.UtcNow.AddMinutes(10),
        Verb = HttpVerb.GET, 
        Protocol = Protocol.HTTPS
    };
    var url = client.GetPreSignedURL(request);
    // ... and return url from here. 
    // Url is valid only for 10 minutes
    // it can be used only to GET content over HTTPS
    // Any other operation like POST would fail.
}
Run Code Online (Sandbox Code Playgroud)

  • 杰出的!工作起来就像一个魅力 (2认同)