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文件。以下是一个示例代码:

import React from 'react';

class DownloadJSON extends React.Component {
  handleDownload = () => {
    fetch('your_api_endpoint', { method: 'GET' })
      .then(response => response.blob())
      .then(blob => {
        // 创建一个临时的URL对象
        const url = window.URL.createObjectURL(new Blob([blob]));

        // 创建一个虚拟的a标签,并设置href属性为临时URL对象的值
        const link = document.createElement('a');
        link.href = url;

        // 设置下载文件名
        link.setAttribute('download', 'OPHotelListAdvertising_???_240628192348584_240628192348584.json');

        // 触发点击事件,开始下载
        document.body.appendChild(link);
        link.click();

        // 下载完成后,清除临时URL和虚拟a标签
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      });
  };

  render() {
    return (
      <button onClick={this.handleDownload}>
        Download JSON
      </button>
    );
  }
}

export default DownloadJSON;

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?