Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get a file stream to download to the browser in Blazor?

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

like image 669
Abdullah Avatar asked Oct 23 '19 16:10

Abdullah


People also ask

Can Blazor access file system?

The API makes it possible to read and write to your local file system from the browser both files and directories. The API is supported on a limited set of browsers.

What is @inject in Blazor?

Dependency injection (DI) is a technique for accessing services configured in a central location: Framework-registered services can be injected directly into components of Blazor apps. Blazor apps define and register custom services and make them available throughout the app via DI.


2 Answers

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);
}
like image 145
Softlion Avatar answered Sep 22 '22 09:09

Softlion


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.

like image 25
yopez83 Avatar answered Sep 22 '22 09:09

yopez83