【发布时间】:2021-05-31 04:33:43
【问题描述】:
尝试了不同的标题解决方案,但无法设置下载文件的文件名:
NodeJs 服务器端(快递):
res
.set('content-disposition', `attachment; filename="${filename}"; filename*=UTF-8''${encodeURI(filename)}`) // filename header
.type('.xlsx') // setting content-type to xlsx. based on file extention
wb.write(filename, res);
客户端(React + JS):
const options = {
headers: {
'Content-Disposition': 'attachment; filename="filename.xlsx";'
}
};
fetch("/api", options)
.then( res => res.blob() )
.then( blob => {
var file = window.URL.createObjectURL(blob);
window.location.assign(file);
});
我在客户端收到了正确的文件,但文件名类似于“93e43995-e4c2-4184-af62-a268d0b456e2.xlsx”。
在客户端控制台(网络选项卡)我可以看到:
Request URL: blob:https://192.168.0.34:8443/e60d73fb-b423-4176-beb3-103028f8f225
Request Method: GET
Status Code: 200 OK
Referrer Policy: strict-origin-when-cross-origin
Content-Length: 5823
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Provisional headers are shown
Upgrade-Insecure-Requests: 1
如何设置标题以设置文件名?某处可能是错误的语法?请不要提供带有 JS a href 对象的答案,例如 a.click。这与我的情况不兼容。
Apoorva 的更新,谢谢,看起来不错,但出现了一些错误:
Unexpected token, expected ","
252 | const filename = response.headers.get('Content-Disposition').split('filename=')[1];
253 | return {response: res.blob(), filename: filename}})
> 254 | .then( ({response, filename} => {
| ^
请再检查一次好吗?
【问题讨论】:
标签: javascript node.js reactjs express