Reputation: 19
I created a button on a Radzen page to download a file inside the wwwroot
folder. This file is related to a row inside my table on SQL Server database (table name is : Tbl_Tickets
).
The file path and file name is saved inside my table in SQL Server database. I created an object of the table named it (tblTicket
) to filter inside my wwwroot
folder by ticket_Id
column.
This is the error that I'm receiving:
Not allowed to load local resource: file:///C:/Users/Administrator/source/repos/Tickets/V05/wwwroot
This is the code of the button in my Blazor page:
<RadzenRow>
<button @onclick="DownloadFileFromURL"> Download Files</button>
</RadzenRow>
This is the function of DownloadFileFromURL:
<script>
window.triggerFileDownload = (fileName, url) => {
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}
</script>
And this is the code:
@code {
private async Task DownloadFileFromURL()
{
var fileName = $"{tblTicket.AttchedFileName}";
var fileURL = $"{environment.WebRootPath}";
await JS.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);
}
And for you information I Injected this
@inject IJSRuntime JS
@inject IWebHostEnvironment environment
Upvotes: -1
Views: 215
Reputation: 27154
This is a security issue. Today, most browsers do not allow accessing file://
URLs in a http(s)://
webpage.
Although there are some workarounds (such as using extensions or encoding files as base64), the best practice is to host the file you want to download on a website and then use a http(s)://
URL to access it.
If this wwwroot
folder is the root folder of your running website, you can simply set:
anchorElement.href = '/' + fileName;
Upvotes: 3