ZBLOG

Cache-Control: no-cache, no-store, max-age=0, must-revalidate Connection: keep-alive Content-Disposition: attachment; filename=OPHotelListAdvertising_???_240628192348584_240628192348584.json Content-Length: 2775 Content-Type: application/octet-str...

在React中,你可以使用fetch或者axios等库来下载JSON文件。以下是一个示例代码:

  1. import React from 'react';
  2. class DownloadJSON extends React.Component {
  3. handleDownload = () => {
  4. fetch('your_api_endpoint', { method: 'GET' })
  5. .then(response => response.blob())
  6. .then(blob => {
  7. // 创建一个临时的URL对象
  8. const url = window.URL.createObjectURL(new Blob([blob]));
  9. // 创建一个虚拟的a标签,并设置href属性为临时URL对象的值
  10. const link = document.createElement('a');
  11. link.href = url;
  12. // 设置下载文件名
  13. link.setAttribute('download', 'OPHotelListAdvertising_???_240628192348584_240628192348584.json');
  14. // 触发点击事件,开始下载
  15. document.body.appendChild(link);
  16. link.click();
  17. // 下载完成后,清除临时URL和虚拟a标签
  18. document.body.removeChild(link);
  19. window.URL.revokeObjectURL(url);
  20. });
  21. };
  22. render() {
  23. return (
  24. <button onClick={this.handleDownload}>
  25. Download JSON
  26. </button>
  27. );
  28. }
  29. }
  30. export default DownloadJSON;

上述代码通过发送GET请求获取到JSON数据,并将其转换成Blob对象。然后创建一个临时的URL对象,并将其赋值给虚拟的a标签的href属性。接下来,设置下载文件名和触发点击事件即可开始下载。最后,下载完成后清除临时URL和虚拟a标签。

请替换示例代码中的”your_api_endpoint”为实际的API地址。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16087

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?