【问题标题】:Download file from data of an API response with react-admin使用 react-admin 从 API 响应的数据中下载文件
【发布时间】:2020-03-12 13:28:53
【问题描述】:

我正在尝试在我的 react-admin 面板的 AppBar 中创建一个自定义按钮来下载数据库的转储。 API 的响应是一个 json,其中包含有关请求的信息以及数据库的内容。

如何使用包含数据的 json 字段从客户端开始下载? 我暂时这样做了:

const CustomAppBar = withStyles(styles)(({ classes, ...props }) => {
  const dumpDatabase = () => {
    fetch(config['api_url'] + '/dump', { method: 'GET' })
    .then(data =>  data.json())
    .then((json) => {
      console.log(json['data']);
    });
  }

  return (
    <AppBar {...props}>
      <Typography
            variant="inherit"
            color="inherit"
            className={classes.title}
            id="react-admin-title"
      />
      <span className={classes.spacer} />
      <Tooltip title="Dump Database">
        <IconButton color="inherit" onClick={dumpDatabase} >
          <SaveIcon />
        </IconButton>
      </Tooltip>
    </AppBar>
  );
});

console.log(json['data']); 是我试图替换为下载的部分。一般来说,我对 reat-admin 和 javascript 的经验非常低...

【问题讨论】:

    标签: reactjs react-admin


    【解决方案1】:

    一段时间后,我找到了一个可以使用的可行解决方案。您必须创建一个 blob 对象并将其分配给一个链接,然后通过脚本自动单击它。

    dumpDatabase = () => {
        fetch(config['api_url'] + '/dump', { method: 'GET' })
        .then(data =>  data.json())
        .then(json => {
          if (json['result'] === 'success')
          {
              // Creating the blob file and its url
              var blob = new Blob([json['data']], {type: 'application/json'}); 
              let url = window.URL.createObjectURL(blob);
    
              var date = Moment(new Date()).format("YYYY_MM_DD-HH_mm_ss");
    
              // Creating the hyperlink and auto click it to start the download
              let link = document.createElement('a');
              link.href = url;
              link.download = 'dump_' + date + '.json';
              link.click();
          }
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 2019-08-29
      • 2019-12-26
      • 2020-02-26
      • 2020-03-22
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多