Blazor WASM Hosted - How to download a file using HttpPost

1.5k views Asked by At

I have a Blazor WASM hosted app that has an API endpoint that accepts a model in the body. The Controller then converts the model's properties into a PDF and returns a FileStreamResult.

Since I have request body content, it must be an HttpPost method; however, I've only seen examples that use HttpGet to invoke the download.

As it stands now, I am only getting the pdf binary data in the response content. Can I trigger the browser download using this setup? Or do I need to manually convert the byte[] to a File on the client?

Server Controller:

[HttpPost("DownloadPdf")]
public async Task<FileStreamResult> DownloadPdf(DownloadPdfModel model)
{
    try
    {
        var title = $"{model.Id}-{model.Description}";
        var filename = $"{title}.pdf";
        var doc = await _pdfService.HtmlToPdf(model.Html);

        return File(doc.Stream, "application/pdf", filename);
    }
    catch (Exception)
    {
        return null;
    }
}

Client Http service:

public async Task DownloadPdf(DownloadPdfModel model)
{
    var content = new StringContent(JsonConvert.SerializeObject(model), System.Text.Encoding.UTF8, "application/json");

    using var response = await _httpClient.PostAsync("api/FooBar/DownloadPdf", content);

    response.EnsureSuccessStatusCode();

    var result = await response.Content.ReadAsStreamAsync();
    // Can I invoke the browser download here or manually using System.IO?
}
1

There are 1 answers

1
Paul On BEST ANSWER

You can use this package : https://github.com/arivera12/BlazorDownloadFile. Here is some sample code where httpResponseMessage is the response from the server containing the file contents and it "downloads" it as an Excel file in the browser, in my case.

            if (httpResponseMessage.IsSuccessStatusCode)
            {
                byte[] bytes = await httpResponseMessage.Content.ReadAsByteArrayAsync();

                await BlazorDownloadFileService.DownloadFile("filename.xlsx",
                    bytes,
                    contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            }