Reputation: 121
I'm writing a Blazor WebServer application which, at one point, allows the client to download a file. This file is forwarded from another API, which offers it as an application/octet-stream
message, and according to the code snippet found in https://learn.microsoft.com/en-us/aspnet/core/blazor/file-downloads?view=aspnetcore-8.0, the block of code responsible of initiating the download looks like this
// stuff
using var client = new HttpClient();
var response = await client.GetAsync(url_of_file);
if(response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadAsStreamAsync();
var streamRef = new DotNetStreamReference(stream: result);
await JS.InvokeVoidAsync("downloadFileFromStream", name_of_file, streamRef);
}
// stuff
Even though the files are not too big, I don't quite like this way of proceeding, as I believe that response.Content.ReadAsStreamAsync
is loading the full content of the response into memory before forwarding it to the client, as its result is a MemoryStream. This is not desirable, as it is introducing a delay before the download starts (the time required for the server to fully download the file), and I'm concerned of the impact to memory once several users try downloading at the same time.
I can't just redirect the client to the API producing the file, which would seem to be the obvious solution, as part of the 'raison d'être' of my server is that the API is accessible through my application, but not by the end users. Is there an easy way for me to just forward to the client the result of the API request (i.e., kind of piping the content of response
into a Stream
without just fully loading it into memory all at once)?
What I tried: The code provided is the last iteration of my attempts.
What I expected:
I expected that the Stream
obtained at await response.Content.ReadAsStreamAsync()
would be an IO stream with the data coming from the HTTP messages from the API.
What I found:
Instead, I found it to be a MemoryStream
that contains the full result of the communication, which is not desirable, as I don't want it to be fully placed into memory in my server, nor wait for it to be fully downloaded to the server before starting the download at the client.
Upvotes: 2
Views: 188