为了账号安全,请及时绑定邮箱和手机立即绑定

如何创建 json 文件,然后在 get 请求中将其返回给 React 应用程序

如何创建 json 文件,然后在 get 请求中将其返回给 React 应用程序

九州编程 2024-01-28 16:43:10
我正在尝试创建一个 JSON 文件sample.json,并且我正在尝试在 Spring Boot 后端控制器中创建此文件,并能够将其发送到我的 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 请求在后端生成文件并能够触发下载,请告诉我这是如何实现的。谢谢。
查看完整描述

1 回答

?
慕标琳琳

TA贡献1830条经验 获得超9个赞

最简单的方法是不使用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);

});


查看完整回答
反对 回复 2024-01-28
  • 1 回答
  • 0 关注
  • 26 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信