gpt4 book ai didi

javascript - 如何从浏览器FETCH触发浏览器下载?

转载 作者:行者123 更新时间:2023-12-01 18:01:47 24 4
gpt4 key购买 nike

我正在开发一个项目,前端使用 Vue.jsTypescript,后端使用 Java Spring

我的 java Controller 从数据库检索给定的报告,然后将其复制到 HTML 响应中。我希望浏览器下载 CSV,因此我在响应中添加了 Content-disposition header 。

     @GetMapping('/download')
public void downloadCSV(HttpServletRequest response){
Report r = reportService.findById(85);
response.addHeader("Content-Disposition", "attachment; filename=myCSV.csv");
response.setContentType("text/csv");

try {
InputStream stream = new ByteArrayInputStream(r.getDocument());
IOUtils.copy(stream, response.getOutputStream());
response.flushBuffer();
} catch(Exception e) {...}
}

我有 2 个按钮:一个简单的超链接标签,其 href 链接到 download(),以及一个 b 按钮(来自 bootstrap-vue),一旦点击就会触发 download2() em>.

   <a :href="download" role="button"> Download CSV </a>

<b-button @click="event => download2()">
Download CSV v2
</b-button>
    get download(): string {
return 'http://localhost:8080/download';
}


async download2() {
const rHeaders = new Headers();
rHeaders.append('Accept', 'text/csv');

const configInit = RequestInit = {
method: 'GET',
headers: rHeaders
};

try {
const res = await fetch('http://localhost:8080/download', configInit);
return res.text();
} catch (e) {...}
}

现在,如果我单击第一个按钮“下载 csv”,浏览器就会正确下载 csv。 JavaScript 控制台打印以下内容:

Resource interpreted as Document but transferred with MIME type text/csv

响应正文中没有任何内容。

相反,如果我单击第二个按钮“下载 csv v2”,下载不会开始,但响应正文中有 csv。

这里是两者请求头的区别。

*Header*                   *Download csv*        *Download csv v2*
Sec-Fetch-Dest document empty
Sec-Fetch-Mode navigate cors
Sec-Fetch-User ?1 -
Upgrade-Insecure-Requests 1 -

其他 header 相同。即使我在 javascript 方法中设置了这些 header ,也不可能更改它们;它们仍然保持不变。有什么问题?谢谢。

最佳答案

我通过“模仿” <a> 的行为找到了解决方案元素:

这样就可以正常工作了:

async download2() {
const configInit: RequestInit = {
method: 'GET'
};

try {
await fetch('http://localhost:8080/download', configInit)
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'report.csv';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
} catch (e) {...}

关于javascript - 如何从浏览器FETCH触发浏览器下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616035/

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