简体   繁体   English

如何让用户在React中下载数据(CSV)?

[英]How to let the user download data (CSV) in React?

I'm using React to create a PWA (meaning it should ideally be usable on mobile and in the browser). 我正在使用React创建一个PWA(这意味着它应该理想地在移动设备和浏览器中可用)。 I have a button in my drawer (burger menu) that should let the viewer download a CSV file. 我在抽屉中有一个按钮(汉堡菜单),查看器应该可以下载CSV文件。

import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
// ... 

<ListItem
  button
  onClick={handleExport}
  className="drawer-export-contacts-button"
>
  <ListItemIcon>
    <ShareIcon />
  </ListItemIcon>
  <ListItemText primary={strings.exportContacts} />
</ListItem>

I have a function that prepares the CSV data as a Blob but I can't figure out how to trigger the download. 我有一个将CSV数据准备为Blob的功能,但我不知道如何触发下载。

function handleExport() {
  const csv = convertContactsToCSV(contacts);
  const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  // ...
}

How can you let the user download data? 您如何让用户下载数据?

You can use FileSaver, which is a great tool to manage files on client-side. 您可以使用FileSaver,这是在客户端管理文件的好工具。

Your code should look like this: 您的代码应如下所示:

import FileSaver from 'file-saver';

function handleExport() {
  const csv = convertContactsToCSV(contacts);
  const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

  FileSaver.saveAs(csvData, 'data.csv');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM