简体   繁体   English

javascript - 让浏览器发送 PDF 文件到下载文件夹

[英]javascript - make browser send PDF file to download folder

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?如何将从服务器下载的 PDF 文件发送到浏览器的下载区,而不是在浏览器 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):我正在使用 Blazor 中的 C#。这是我当前的代码,我需要修改它,但不知道如何修改(我在这里问之前用 google 搜索过):

    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.服务器在此处返回一个 FileStreamResult,浏览器在新选项卡中显示该文件。 I want it to send it to its downloads folder instead.我希望它将它发送到它的下载文件夹。

You are invoking a JS Function called "open" with two params.您正在使用两个参数调用名为“open”的 JS Function。 ( https://developer.mozilla.org/en-US/docs/Web/API/Window/open ) ( 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.尝试在脚本文件/标签内创建您自己的 JS 下载 function 并调用它。

The crucial part to save a file in the downloads folder is to set the download attribute of the a tag.将文件保存在下载文件夹中的关键部分是设置a标签的download属性。
It could look something like this.它可能看起来像这样。

inside wwwroot/index.html :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:在您的 blazor 组件中:

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.如果在用户浏览器中进行了配置,该文件仍会打开,但它也会存储在下载文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM