【问题标题】:How do you trigger a file download in React? [duplicate]你如何在 React 中触发文件下载? [复制]
【发布时间】:2021-04-01 13:22:36
【问题描述】:

我在 React 中创建了一个 Web 应用程序。大多数 URL 都需要身份验证(Bearer)。 API 端点之一是下载 ZIP 文件。我不确定如何触发文件在客户端浏览器上下载。我不能做 <a> 因为它需要 Bearer 令牌。 React 应用程序可以下载它,但是我如何触发浏览器接受下载?谢谢。

【问题讨论】:

标签: javascript


【解决方案1】:

以下是触发下载的方式:

fetch("https://yourfiledownload.api/getfile", {
        method: "POST",
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer XXXXXXXXXXX'
        }
    })
        .then(response => {
            const disposition = response.headers.get("content-disposition");
            filename = disposition.match(/filename=(.+)/)[1];
            return response.blob()
        })
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const 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
            callback({msg: 'ok'})
        })

这假设您的 API 会发回正确的内容,包括标头。例如,在 CSV 文件的情况下是这样的:

res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.set('Content-Type', 'text/csv');

res.write("Some Data here");
res.end();

请注意,Content-Disposition 是必需的,以便文件名由您的 API 确定并发送回客户端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2016-08-22
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多