I have created an HttpGet in my Server-API which creates a CSV-File and returns it with FileStreamResult:
[HttpGet]
public IActionResult Get() {
// do logic to create csv in memoryStream
return new FileStreamResult(memoryStream, "text/csv;charset=utf-8") {
FileDownloadName = "products.csv",
};
}
In my Blazor-Client App, I have created a Button with a handler:
private async Task DownloadCatalog() {
var file = HttpClient.GetAsync("api/csvProduct");
// ... how do I download the file in the browser?
}
The Get in the Controller is called, but I don't know what to do so that the file is downloaded in the browser after the api call.
When you do HttpClient.GetAsync the Blazor runtime gets the file. But it cannot directly save the file to the disk as a Browser environment (in which Blazor runs) does not have access to the disk.
So you will have to use some Javascript Interop to trigger the file download feature of the browser. You can generate a link data:text/plain;charset=utf-8,<<content of the file>> and invoke click on it.
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 to get the file as byte array then convert it to base64string. Finally call the function that you created in javascript.
In server side
js.InvokeVoidAsync("jsSaveAsFile",
filename,
Convert.ToBase64String(GetFileByteArrayFunction())
);
And in javascript file in wwwroot you create a function
function jsSaveAsFile(filename, byteBase64) {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + byteBase64;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
use the NavigationManager
@inject NavigationManager NavigationManager
private async Task DownloadCatalog() {
NavigationManager.NavigateTo("api/csvProduct",true);
}