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");
}
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.
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);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With