Javascript 如何在React中触发文件下载?
我在React中创建了一个Web应用程序。大多数URL都需要身份验证(承载)。API端点之一是下载ZIP文件。我不确定如何触发文件在客户端浏览器上下载。我不能执行Javascript 如何在React中触发文件下载?,javascript,Javascript,我在React中创建了一个Web应用程序。大多数URL都需要身份验证(承载)。API端点之一是下载ZIP文件。我不确定如何触发文件在客户端浏览器上下载。我不能执行,因为它需要承载令牌。React应用程序可以下载,但如何触发浏览器接受下载?Thx.以下是触发下载的方式: fetch("https://yourfiledownload.api/getfile", { method: "POST", headers: {
,因为它需要承载令牌。React应用程序可以下载,但如何触发浏览器接受下载?Thx.以下是触发下载的方式:
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确定并发送回客户端。这似乎与React无关。看看@FelixKling Thx,我去掉了react标签。