如何在js函数中添加授权token来实现下载文件功能?

问题描述 投票:0回答:1

我有一个blazor客户端,有一个功能需要下载文件。

我查看了此参考资料。如果我将 API 端点设置为允许匿名,它就会起作用。但是当我使用

[Authorize]
设置 API 端点时,我不知道如何将不记名令牌传递给请求。

我可以将令牌传递给函数的最后一个参数

triggerFileDownload
,但不知道如何将其放入请求中。

我尝试了以下方法,但没有成功,得到了 401 Unauthorized:

window.triggerFileDownload = (fileName, url, token) => {

const anchorElement = document.createElement('a');
createCookie('Authorization', 'Bearer ' + token, 1);//this line didn't work
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}


function createCookie(name, value, days) {
var expires;
if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
}
else {
    expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}

当我在浏览器中打开“网络”选项卡时,我看到:

请问有人可以建议如何将令牌传递给此函数的请求吗?我认为这需要在标有注释的代码中完成(//此行不起作用)。

提前致谢。

javascript blazor authorization unauthorized
1个回答
2
投票

授权标头应该在标头中传递,我认为当您单击按钮时不可能直接传递。 另一种方法是使用 xhr 调用来下载文件并传递授权不记名令牌

<html>
    <head>
        <script>
            const origin = location.origin;
            const filename = 'fileToDownload.csv';
            const token = 'XXXXXXXX';
            function downloadFile() {
                const fileUrl = [origin, filename].join('/');
                fetch(fileUrl, {
                    method: 'GET',
                    headers: new Headers({
                        'Authorization': 'Bearer ' + token
                    })
                })
                .then(function (response) { return response.blob();})
                .then(function (blob) {
                    var url = window.URL.createObjectURL(blob);
                    console.log(url);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a); // we need to append the element to the dom -> otherwise it will not work in firefox
                    a.click();    
                    a.remove();  //afterwards we remove the element again  
                });
            }
        </script>
    </head>
    <body>
        <h1>Download file</h1>
        <div>
            <button onclick="downloadFile()" type="button">download file</button>
         </div>
    </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.