1

I would like to be able to download files via links in my web app. I am using Amazon S3 to store files in the cloud and am able to retrieve them into a ResponseStream using the example here:

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

How do I go from having a ResponseStream to actually being able to download the file in the browser? I do not want to download it to the server, and I want to to be downloaded to the user's downloads folder. I feel like I do not know enough about how to do this to know where to start.

            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?

                }
            }
F Horm
  • 13
  • 3
  • Does this answer your question? [How to stream with ASP.NET Core](https://stackoverflow.com/questions/42771409/how-to-stream-with-asp-net-core) – David Browne - Microsoft Apr 20 '20 at 19:37
  • Create a controller action and a route to your action. That will be the URL where users can download the file. Inside your action you get the data stream as in your example and return the content as described here: https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api – Christoph Lütjen Apr 20 '20 at 19:39

1 Answers1

2

If the stream is the file you want to return, just return the stream directly:

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

Note, however, that you should not use using when getting the stream. ASP.NET Core will take care of disposing the stream when it's done with it, but you need it to persist past the scope of the action.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444