簡體   English   中英

.Net Core - 我如何從 ResponseStream 或 StreamReader go 實際下載前端的文件?

[英].Net Core - How do I go from a ResponseStream or StreamReader to actually downloading the file on the front end?

我希望能夠通過我的 web 應用程序中的鏈接下載文件。 我正在使用 Amazon S3 將文件存儲在雲中,並且能夠使用此處的示例將它們檢索到 ResponseStream 中:

https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html

我如何從擁有 ResponseStream 到實際能夠在瀏覽器中下載文件? 我不想把它下載到服務器上,我想把它下載到用戶的下載文件夾中。 我覺得我對如何做到這一點知之甚少,不知道從哪里開始。

            string responseBody = "";
            try
            {
                GetObjectRequest request = new GetObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName
                };
                using (GetObjectResponse response = await client.GetObjectAsync(request))
                using (Stream responseStream = response.ResponseStream)
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string contentType = response.Headers["Content-Type"];
                    responseBody = reader.ReadToEnd(); // Now you process the response body.

                // I read the response to the end, how do I create a file and download it?

                }
            }

如果 stream 是你要返回的文件,直接返回 stream 即可:

return File(responseStream, response.Headers["Content-Type"]);

但是請注意,在獲取 stream 時不應使用using ASP.NET 內核將在 stream 完成后處理它,但您需要它在操作的 scope 之后持續存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM