gpt4 book ai didi

javascript - 如何从响应中读取文件名-reactJs

转载 作者:行者123 更新时间:2023-12-01 00:42:37 25 4
gpt4 key购买 nike

我正在从服务器下载文件。我在那里设置一个我想在前端读取的文件名。这是我在服务器上执行此操作的方法:

string fileName = "SomeText" + DateTime.UtcNow.ToString() + ".csv";

return File(stream, "text/csv", fileName);

基本上我会返回不同类型的文件,有时csv有时xlsx有时pdf。所以我想在前端获取文件名,以便我可以将其保存为应有的格式,例如 SomeText.pdf 它将自动保存在本地计算机上作为 pdf

这是我的前端代码:

getFileFromServer(params).then(response => {
console.log('server response download:', response);
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });
//const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.xlsx'; // Here I want to get rid of hardcoded value instead I want filename from server
link.click();
link.remove(); // Probably needed to remove html element after downloading?
});

我在“响应 header ”下的“网络”选项卡中看到有一个包含该信息的 Content-Disposition:

Content-Disposition: attachment; filename="SomeText22/08/2019 10:42:04.csv";

但我不知道它在我的回复中是否可用,以及如何在我的前端部分中读取它,以便我可以替换

link.download = 'file.xlsx';

带有来自服务器的路径..

非常感谢大家

干杯

最佳答案

这是一种特殊类型的 header ,因此要在前端获取此 header ,后端人员应该允许从他的一端。然后你可以在响应中的标题

response.headers.get("content-disposition")

下面的代码是我在我的项目中使用的

 downloadReport(url, data) {
fetch("url of api")
.then(async response => {
const filename = response.headers
.get("content-disposition")
.split('"')[1];
const text = await response.text();
return { filename, text };
})
.then(responseText => this.download(responseText))
.catch(error => {
messageNotification("error", error.message);
throw new Error(error.message);
});
}

关于javascript - 如何从响应中读取文件名-reactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com