[英]Get object from AWS S3 as a stream
我試圖弄清楚是否有可能返回我從 AWS S3 存儲桶中獲取的對象的某種流(可能是內存流?)。
S3 存儲桶包含許多不同類型的圖像、文檔等。所有這些都應該在我的網站上使用。 但是,我不想顯示我的 AWS S3 存儲桶的路徑。
這就是為什么我試圖創建一個流並動態顯示圖像和可下載文檔而不是完整路徑的原因。 這有意義嗎? :-)
我正在使用 C#/.NET AWS SDK。
期待聽到所指出的任何想法和方向!
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。
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
的替代方法。
更便宜的方法是使用 S3 中對象的預簽名 URL。 這樣您就可以將過期的 URL 返回給您的資源,而無需進行任何流式復制。 這需要非常低的內存,因此您可以使用非常小且便宜的 VM。
這種方法適用於少數資源和少數客戶。 如果有更多請求,您可能會達到 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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.