Trigger a file download through a PageCommand
Is it possible to trigger a file download from a custom PageCommand
?
I am wanting to extend a listing page (e.g. UserList), and add a new HeaderAction
button which downloads a file.
public class UserListExtender : PageExtender<UserList>
{
public override async Task ConfigurePage()
{
await base.ConfigurePage();
Page.PageConfiguration.HeaderActions.AddCommand(
label: "Download",
command: nameof(MyExtenderCommand),
icon: Icons.Ribbon,
destructive: false
);
}
[PageCommand]
public async Task<ICommandResponse> MyExtenderCommand()
{
// Code here to generate and download a file
return Response().AddSuccessMessage("File ready to download.");
}
}
Since ICommandResponse
only has a collection of messages, I assume this is not really possible.
Environment
- Xperience by Kentico version: [29.6.0]
- .NET version: 8
- Execution environment: Local
- Link to relevant Xperience by Kentico documentation
Answers
I haven't seen an example of how to download a file through a PageCommand
, but here are some things you could try.
- Use
ResponseFrom()
and send the file as binary data (not a stream). Turn the response into aBlob
in the browser. Add an invisible<a href="...">
to the page and "click" it to trigger the download. - Send the URL of the file in
ResponseFrom()
and turn that into a<a href="...">Download</a>
. The user can click it and download the file. - If you need special processing or protection of the file you might need to make an administration authorized ASP.NET Core Controller or endpoint that looks up the file and sends the response. You can then send a request to this endpoint from the client instead of invoking a
PageCommand
.
There's now a prototype example in the Kentico Community Portal which shows how you can send file contents to the browser and initiate a download of the file.
- RecipientListOverviewExtender.cs - creates the
EXPORT_LIST
command called by the client - DataExportComponent.tsx - initiates the file download from a CTA
I'm sure there are many ways to refine this setup, but it "works" and should be able to scale to downloading files up to a hundred MB in size.
To answer this question, you have to login first.