我正在使用 Fetch API 下载文件,执行该操作的代码如下所示:
const response = fetch(`{% url 'export_xls' %}?${urlParams}`,{
method: 'GET',
mode: 'cors',
headers: {
"X-CSRFToken": '{{ csrf_token }}',
}
})
.then(res => res.blob())
.then(blob => {
let file = window.URL.createObjectURL(blob);
window.location.assign(file);
})
这确实会导致下载文件,但是,文件名是随机的,而不是使用 Content-Disposition
标头中给出的文件名。我在 chrome 开发工具中可以看到的标头只有 Content-Length
和 Content-Type
,但是,当我控制台记录响应的标头时,Content-Disposition
标头就在那里。< /p>
使用 fetch API 调用的 django 视图设置了标头,所以我不明白为什么文件名不正确:
response = FileResponse(buffer, as_attachment=True, filename="foo.xlsx")
response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
response['Content-Disposition'] = 'attachment; filename="foo.xlsx'
response['Access-Control-Expose-Headers'] = 'Content-Disposition' # I read it could be a CORS problem and this could solve it, however, no luck
return response
经过一些谷歌搜索后,我发现人们推荐使用 a
标签元素并设置 download
属性的多个线程,但是,由于 Content-Disposition
标头设置正确,我希望使文件具有正确的文件名,而无需在 JS 代码中做任何额外的工作。