Trigger a file download through a PageCommand

2024/10/27 10:58 PM

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

Answers

2024/10/29 12:38 PM

I haven't seen an example of how to download a file through a PageCommand, but here are some things you could try.

  1. Use ResponseFrom() and send the file as binary data (not a stream). Turn the response into a Blob in the browser. Add an invisible <a href="..."> to the page and "click" it to trigger the download.
  2. 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.
  3. 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.
2024/10/29 2:35 PM

Thanks Sean, I'll give these options a go.

My aim here is to allow an export option for the user listing for example, so hopefully this will allow it.

2024/11/05 4:38 PM
Answer

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.

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.