7

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");
}

2 Answers 2

4

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.

0
3

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);}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.