6

I'm trying out a few things with Blazor and I'm still new to it. I'm trying to get a file stream to download to the browser. What's the best way to download a file from Blazor to browser?

I've tried using a method in my razor view that returns a stream but that didn't work.

//In my Blazor view
@code{
    private FileStream Download()
    {
        //get path + file name
        var file = @"c:\path\to\my\file\test.txt";
        var stream = new FileStream(test, FileMode.OpenOrCreate);
        return stream;
    }
}

The code above doesn't give me anything, not even an error

Mike Brind
  • 25,035
  • 6
  • 49
  • 82
Abdullah
  • 103
  • 2
  • 10
  • Do I get it correctly that you want to download a file from the server to the client? Or you want to upload a file for processing, like an image upload? – Zsolt Bendes Oct 24 '19 at 07:25
  • My server(A) is sending out a request to another server(B) to get the file then give it to the browser, at least that's how I wanted it to work. I'm making a web request to another resource and I want it to trigger a browser download – Abdullah Oct 24 '19 at 15:15
  • I mean. . . why not just let users download direct from server (B)? – Bennyboy1973 Sep 17 '21 at 05:11

2 Answers2

9

Another solution is to add a simple api controller endpoint using endpoints.MapControllerRoute. This will work only with server side blazor though.

Ex:

endpoints.MapBlazorHub();
endpoints.MapControllerRoute("mvc", "{controller}/{action}");
endpoints.MapFallbackToPage("/_Host");

Then add a controller. For example:

public class InvoiceController : Controller
{
    [HttpGet("~/invoice/{sessionId}")]
    public async Task<IActionResult> Invoice(string sessionId, CancellationToken cancel)
    {
        return File(...);
    }
}

Usage in a .razor file:

async Task GetInvoice()
{
    ...
    Navigation.NavigateTo($"/invoice/{orderSessionId}", true);
}
Softlion
  • 11,904
  • 10
  • 55
  • 86
1

Although the above answer is technically correct, if you need to pass in a model -POST-, then NavigationManager won't work. In which case you, must likely end up using HttpClient component. If so wrap the response.Content -your stream- in a DotNetStreamReference instance - new DotNetStreamReference(response.Content). This will create a ReadableStream. Then create the blob with the content. Keep in mind DotNetStreamReference was recently introduced with .NET 6 RC1. As of now the most efficient way. Otherwise, you can use fetch API and create a blob from the response.

yopez83
  • 471
  • 4
  • 19