devlife
devlife

Reputation: 16145

How to download a file from blazor server side

I have a server side blazor app which builds up a lot of data and when a user clicks a button will use that data to generate an excel file. All of that is working fine. But my question is what is the appropriate way to download that in-memory file? I know I can save it to the web server disk and do a redirect or something like that to download it I would prefer not to have to save the file to disk if I don't have to.

Upvotes: 7

Views: 19807

Answers (2)

Martin Ch
Martin Ch

Reputation: 1367

You can do something like this

[Route("api/[controller]"]
[ApiController]
public class DownloadController : ControllerBase
{
    [HttpGet, DisableRequestSizeLimit]
    public async Task<IActionResult> Download()
    {
        var memory = new MemoryStream();
        await using(var stream = new FileStream(@"pathToLocalFile", FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        //set correct content type here
        return File(memory, "application/octet-stream", "fileNameToBeUsedForSave");
    }
}

And on a razor side

<button @onclick="onClick">download</button>

@code {

   private async Task onClick(MouseEventArgs e)
   {
        NavigationManager.NavigateTo("api/download", true);
   }
}

Upvotes: 1

devlife
devlife

Reputation: 16145

The solution I ended up using was JS Interop to redirect to the file which then downloaded it.

public async Task DownloadFileAsync(string path)
{
    await Js.InvokeAsync<string>("downloadFile", path);
}

// In JS
function downloadFile(filename) {
    location.href = '/api/downloads/' + filename;
}

Upvotes: 9

Related Questions