作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在从服务器下载文件。我在那里设置一个我想在前端读取的文件名。这是我在服务器上执行此操作的方法:
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/
我是一名优秀的程序员,十分优秀!