问题描述
我试图弄清楚是否有可能返回从我的AWS S3存储桶中获得的对象的某种流(可能是内存流?).
I am trying to to figure out whether it is possbile to return some sort of stream (possibly a memory stream?) of an object I get from my AWS S3 bucket.
S3存储桶包含许多不同类型的图像,文档等.所有这些都应在我的网站上使用.但是,我不想显示我的AWS S3存储桶的路径.
这就是为什么我试图创建一个流并动态显示图像和可下载文档的原因,而不是完整路径.这有意义吗? :-)
The S3 bucket contains a lot of different type of images, documents etc. All those should be used on my website. However, I do not want to display the path to my AWS S3 bucket.
That is why I am trying to create a stream and display the images and downloadable documents on the fly rather than with a full path. Does this make sense? :-)
我正在使用C#/.NET AWS开发工具包.
I am using the C#/.NET AWS SDK.
期待听到所指向的任何想法和指示!
Looking forward to hear about any ideas and directions pointed to!
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
}
}
}
推荐答案
在.NET 4中,您可以使用 Stream.CopyTo 复制ResponseStream的内容(即 Amazon.Runtime.Internal.Util.MD5Stream )到MemoryStream.
In .NET 4, you can use Stream.CopyTo to copy the content of the ResponseStream (that is a Amazon.Runtime.Internal.Util.MD5Stream) to a MemoryStream.
GetObjectResponse response = await client.GetObjectAsync(bucketName, keyName);
MemoryStream memoryStream = new MemoryStream();
using (Stream responseStream = response.ResponseStream)
{
responseStream.CopyTo(memoryStream);
}
return memoryStream;
在其中client.GetObjectAsync(bucketName, keyName)
可以替代正在创建的请求调用GetObject
.
Where client.GetObjectAsync(bucketName, keyName)
is an alternative to calling GetObject
with the request you are creating.
这篇关于以流的形式从AWS S3获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!