The NavigationManager.NavigateTo
is designed to handle page navigation, not file downloads.
You can follow the official document to learn how to file download in Blazor Server
This article covers approaches for the following scenarios, where a file shouldn't be opened by a browser but downloaded and saved on the client:
- Stream file content to a raw binary data buffer on the client: Typically, this approach is used for relatively small files (< 250 MB).
- Download a file via a URL without streaming: Usually, this approach is used for relatively large files (> 250 MB).
For example:
1.Modify Razor Component code
@inject IJSRuntime JS
private async Task DownloadSvg()
{
byte[] svgBytes = Encoding.UTF8.GetBytes(svgContent);
var fileName = "convertedImage.svg";
var base64 = Convert.ToBase64String(svgBytes);
var dataUrl = $"data:image/svg+xml;base64,{base64}";
await JS.InvokeVoidAsync("triggerDownload", dataUrl, fileName);
}
2.Add the JavaScript function in your _Host.cshtml(Assume you are using .NET 7 Blazor Server App)
<body>
//.....
<script src="_framework/blazor.server.js"></script>
<script>
function triggerDownload(dataUrl, fileName) {
const link = document.createElement('a');
link.href = dataUrl;
link.download = fileName;
link.click();
}
</script>
</body>
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Rena