1

How do I send a PDF file I am downloading from a server to the browser's download area instead of opening it in a browser window?

I am working with C# in Blazor. This is my current code, which I need to modify, but don't know how to (ofc I googled before asking here):

    async void DownloadDocument(string apiURL, Guid ID)
    {
        JSRuntime.InvokeAsync<string>("open", $"{apiURL}/GetPDF/{ID}", "_blank");
    }

The server returns a FileStreamResult here and the browser shows the file in a new tab. I want it to send it to its downloads folder instead.

Razzupaltuff
  • 2,250
  • 2
  • 21
  • 37
  • 1
    You can't control this. It's per-browser settings. Some can open PDF in browsers, other can't – Justinas Nov 22 '22 at 09:21
  • 1
    Does this answer your question? [Force download of a file on web server - ASP .NET C#](https://stackoverflow.com/questions/873207/force-download-of-a-file-on-web-server-asp-net-c-sharp) – Justinas Nov 22 '22 at 09:22

1 Answers1

1

You are invoking a JS Function called "open" with two params. (https://developer.mozilla.org/en-US/docs/Web/API/Window/open)

Try creating your own JS download function inside of a script file / tag and invoking it.

The crucial part to save a file in the downloads folder is to set the download attribute of the a tag.
It could look something like this.

inside wwwroot/index.html:

<script>
    window.downloadFile = (fileName, pdfData) => {
        const linkSource = `data:application/pdf;base64,${pdfData}`;
        const downloadLink = document.createElement("a");
        downloadLink.href = linkSource;
        downloadLink.download = fileName;
        downloadLink.click();
        downloadLink.remove();
    }
</script>

and in your blazor component:

async void DownloadDocument(string apiURL, Guid ID)
{
        // call your api to download the file you want to download
        var response = await Http.GetAsync($"{apiURL}/GetPDF/{ID}"));
        // convert to base64
        var pdfExportBytes = await response.Content.ReadAsByteArrayAsync();
        var pdfExportB64 = Convert.ToBase64String(pdfExportBytes);
        // invoke js download
        await JSRuntime.InvokeVoidAsync("downloadFile", "FileName", pdfExportB64);
}

The file will still be opened if configured so in the users browser, but it will also be stored in the download folder.

Dany
  • 61
  • 4