我正在尝试创建一个 JSON 文件sample.json,并且我正在尝试在 Spring Boot 后端 Controller 中创建此文件,并能够将其发送到我的 React 应用程序,在那里它将触发将文件下载到客户端
我想确保我实际上从 http get 请求给出的响应返回实际文件,并且我想知道如何触发实际响应的下载 react
fetch('/api/download')
.then((res) => {
return res.blob();
}).then((body) => {
console.log(body);
setTimeout(() => {
URL.createObjectURL(body)
}, 300);
}).catch((error) => {
console.log(error);
})
我的最终目标是能够通过 get 请求在后端生成文件并能够触发下载,请告诉我这是如何实现的。谢谢。
最佳答案
最简单的方法是不使用 fetch
但使用普通的链接元素:
<a href="/api/download" download="sample.json">Click to download</a>
在所有现代浏览器中,download
属性将使浏览器将链接响应保存为文件。否fetch
必填。
但是,如果您绝对需要 fetch
操作,那么你基本上可以在 JS 本身中执行此操作:获取结果,然后创建一个 <a>
,设置其href
属性到文件 blob,并确保 download
属性设置:
fetch(...)
.then(res => res.blob())
.then(blob => {
const blobURL = URL.createObjectURL(blob);
// create our <a> to force a download for the response
const dl = document.createElement(`a`);
dl.href = blobURL;
dl.download = `sample.json`;
// In order for the link to "trigger" we need to add it to the document.
// If we don't, dl.click() won't do anything. So add it, click it, then remove it.
dl.style.display = `none`;
document.body.appendChild(dl);
dl.click();
document.body.removeChild(dl);
});
关于java - 如何创建 json 文件,然后在 get 请求中将其返回给 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666421/