Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blazor webassembly download file from api

I have a Blazor Webassembly ASP.NET Core hosted app, on the server I have a controler that returns a File, and on the Client I would like to have a button that when the user clicks on it download the file, How Can I achive this?

This is my Controller

[HttpGet("{reportName}")]
public FileResult GetReport(string reportName)
{
     var stream = _reportPrintRepository.Print(reportName);

     return File(stream, System.Net.Mime.MediaTypeNames.Application.Pdf, reportName + ".pdf");
}
like image 509
Luis Zenteno Avatar asked Jun 26 '26 21:06

Luis Zenteno


2 Answers

The simplest way is to let the browser handle it:

<a class="btn btn-primary" href="@(Http.BaseAddress)YourController/Test1">download</a>

You get the base address from an inject HttpClient and make sure the URL matches the route you configured in the Controller.

like image 84
Henk Holterman Avatar answered Jun 29 '26 20:06

Henk Holterman


In order to download file you have to use Microsoft JSInterop. There are many ways to implement your request. One way that i use is get the file as byte array then convert to base64string. Finally call the function that you created in javascript from server.

In server side

js.InvokeVoidAsync("jsOpenIntoNewTab",
                            filename,
                            Convert.ToBase64String(ReportPDF())
                            );

In client side in js file

function jsOpenIntoNewTab(filename, byteBase64) {
var blob = b64toBlob(byteBase64);

var blobURL = URL.createObjectURL(blob);
window.open(blobURL);}
like image 40
Baskovli Avatar answered Jun 29 '26 20:06

Baskovli